SlideShare ist ein Scribd-Unternehmen logo
1 von 51
•
•
•
•
def application(environ, start_response):
status = '200 OK'
output = 'Hello World!'
response_headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
WSGIScriptAlias / /path/to/megasite/mysite.wsgi
•
•
•
from cgi import parse_qs, escape
index_html = """<html>...</html>"""
about_html = """<html>...</html>"""
contact_html = """<html>...</html>"""
def application(environ, start_response):
# Returns a dictionary containing lists as values.
d = parse_qs(environ['QUERY_STRING'])
# In this idiom you must issue a list containing a default value.
page = d.get('page', [''])[0] # Returns the first page value.
# Always escape user input to avoid script injection
page = escape(page)
if page == 'about':
response_body = about_html
elif page == 'contact':
response_body = contact_html
else:
response_body = index_html
status = '200 OK'
response_headers = [('Content-Type', 'text/html'),
('Content-Length', str(len(response_body)))]
start_response(status, response_headers)
return [response_body]
•
•
•
•
•
app = Flask(__name__)
@app.route('/')
def index_page():
db = get_db()
cur = db.execute('select title, text from entries order by id desc')
entries = cur.fetchall()
return render_template('show_entries.html', entries=entries)
@app.route('/contact/')
def contact_page():
return render_template('contact_page.html')
•
•
•
•
Model-view-controller – схема использования нескольких шаблонов
проектирования, с помощью которых модель данных приложения,
пользовательский интерфейс и взаимодействие с пользователем
разделены на три отдельных компонента так, что модификация
одного из компонентов оказывает минимальное воздействие на
остальные.
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
myblog/
manage.py
myblog/
__init__.py
settings.py
urls.py
wsgi.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'blog',
'USER': 'root',
'PASSWORD': '1',
'HOST': '',
'PORT': '',
}
}
blog/
__init__.py
models.py
tests.py
views.py
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'blog',
)
•
•
•
•
from django.db import models
import datetime
class Category(models.Model):
title = models.CharField(max_length=255)
description = models.TextField(blank=True)
def __unicode__(self):
return self.title
@models.permalink
def get_absolute_url(self):
return ('category_detail', (self.pk,))
class Post(models.Model):
title = models.CharField(max_length=255)
content = models.TextField()
category = models.ForeignKey(Category)
creation_date =
models.DateTimeField(default=datetime.datetime.now)
def previous_post(self):
"""Return the previous entry"""
def next_post(self):
"""Return the next entry"""
def __unicode__(self):
return self.title
@models.permalink
def get_absolute_url(self):
return ('post_detail', (self.pk,))
class Meta:
ordering = ['-creation_date']
>>> from blog.models import Category, Post
>>> Category.objects.all()
[]
>>> c = Category(title="Python")
>>> c.save()
>>> c.id
1
>>> c.title="About Python"
>>> c.save()
>>> Category.objects.all()
[<Category: About Python>]
>>> Category.objects.filter(id=1)
[<Category: About Python>]
>>> c = Category.objects.get(id=1)
<Category: About Python>
>>> c.post_set.all()
[]
>>> c.post_set.create(title="New post", content="Many words")
<Post: New post>
>>> c.post_set.count()
1
>>> c.delete()
•
•
•
def post_list(request):
object_list = Post.objects.all()
return render(
request, 'blog/post_list.html',
{'object_list': object_list}
)
def post_detail(request, pk):
try:
object = Post.objects.get(pk=pk)
except Post.DoesNotExist:
raise Http404
return render(
request, 'blog/post_detail.html',
{'object': object}
)
def category(request, pk):
cat = get_object_or_404(Category, pk=pk)
post_list = Post.objects.filter(category=cat)
return render(request, 'blog/category.html', {
'category': cat,
'post_list' : post_list
})
from django.conf.urls import patterns, url
urlpatterns = patterns('blog.views',
(r'^$', 'post_list'),
url(r'^post/(?P<pk>d+)/$', 'post_detail',
name='post_detail'),
url(r'^category/(?P<pk>d+)/$', 'category',
name='category_detail'),
)
import os
def rel(*x):
return
os.path.join(os.path.abspath(os.path.dirname(__file_
_)), * x)
TEMPLATE_DIRS = (
rel('../templates'),
)
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=utf-8">
<title>Блог</title>
</head>
<body>
<h1>Мой блог</h1>
{% block content %}{% endblock %}
</body>
</html>
{% extends "base.html" %}
{% block content %}
<ul>
{% for object in object_list %}
<li><a href="{{ object.get_absolute_url
}}">{{ object }}</a> {{
object.created_date|date:"d.m.Y" }}</li>
{% endfor %}
</ul>
{% endblock %}
{% extends "base.html" %}
{% block content %}
<h2>{{ object }}</h2>
<p><small>{{ object.creation_date }} <a
href="{{ object.category.get_absolute_url}}">{{
object.category }}</a></p>
<div>{{ object.content }}</div>
{% endblock %}
{% extends "base.html" %}
{% block content %}
<h2>{{ category }}</h2>
<ul>
{% for object in post_list %}
<li><a href="{{
object.get_absolute_url}}">{{ object }}</a></li>
{% endfor %}
</ul>
{% endblock %}
from django import forms
class ContactForm(forms.Form):
email = forms.EmailField(label=u'Ваш e-mail',
max_length=100)
message = forms.CharField(label=u'Сообщение',
widget=forms.Textarea)
from blog.forms import ContactForm
from django.core.mail import send_mail
from django.http import HttpResponseRedirect
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
subject = u'Сообщение с блога'
message = form.cleaned_data['message']
sender = form.cleaned_data['email']
recipients = ['a.bekbulatov@corp.mail.ru']
send_mail(subject, message, sender, recipients)
return HttpResponseRedirect('/')
else:
form = ContactForm()
return render(request, 'blog/contact.html', {
'form': form
})
urlpatterns = patterns('blog.views',
(r'^$', 'post_list'),
url(r'^post/(?P<pk>d+)/$', 'post_detail',
name='post_detail'),
url(r'^category/(?P<pk>d+)/$', 'category',
name='category_detail'),
(r'^contacts/$', 'contact'),
)
{% extends "base.html" %}
{% block content %}
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Отправить" />
</form>
{% endblock %}
from django import template
from blog.models import Post
register = template.Library()
@register.inclusion_tag('blog/tags/last_posts.html')
def last_posts():
return {'post_list': Post.objects.all()[:5]}
<ul>
{% for object in post_list %}
<li><a href="{{ object.get_absolute_url}}">{{
object }}</a></li>
{% endfor %}
</ul>
{% load blog_tags %}
{% last_posts %}
•
•
•
•
•
•
•
•
•
•
Web осень 2012 лекция 6

Weitere ähnliche Inhalte

Was ist angesagt?

Web2py Code Lab
Web2py Code LabWeb2py Code Lab
Web2py Code Lab
Colin Su
 
Web осень 2012 лекция 7
Web осень 2012 лекция 7Web осень 2012 лекция 7
Web осень 2012 лекция 7
Technopark
 
Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.
fRui Apps
 

Was ist angesagt? (20)

Cfml features modern coding into the box 2018
Cfml features modern coding into the box 2018Cfml features modern coding into the box 2018
Cfml features modern coding into the box 2018
 
PHP webboard
PHP webboardPHP webboard
PHP webboard
 
Phoenix + Reactで 社内システムを 密かに作ってる
Phoenix + Reactで 社内システムを 密かに作ってるPhoenix + Reactで 社内システムを 密かに作ってる
Phoenix + Reactで 社内システムを 密かに作ってる
 
ERRest in Depth
ERRest in DepthERRest in Depth
ERRest in Depth
 
PHP cart
PHP cartPHP cart
PHP cart
 
テストデータどうしてますか?
テストデータどうしてますか?テストデータどうしてますか?
テストデータどうしてますか?
 
Web2py Code Lab
Web2py Code LabWeb2py Code Lab
Web2py Code Lab
 
Web осень 2012 лекция 7
Web осень 2012 лекция 7Web осень 2012 лекция 7
Web осень 2012 лекция 7
 
Using Scala Slick at FortyTwo
Using Scala Slick at FortyTwoUsing Scala Slick at FortyTwo
Using Scala Slick at FortyTwo
 
Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access
 
Leveraging Symfony2 Forms
Leveraging Symfony2 FormsLeveraging Symfony2 Forms
Leveraging Symfony2 Forms
 
How te bring common UI patterns to ADF
How te bring common UI patterns to ADFHow te bring common UI patterns to ADF
How te bring common UI patterns to ADF
 
Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.
 
Everything you always wanted to know about forms* *but were afraid to ask
Everything you always wanted to know about forms* *but were afraid to askEverything you always wanted to know about forms* *but were afraid to ask
Everything you always wanted to know about forms* *but were afraid to ask
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntity
 
ERRest - The Next Steps
ERRest - The Next StepsERRest - The Next Steps
ERRest - The Next Steps
 
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark BrocatoSenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
ERRest - Designing a good REST service
ERRest - Designing a good REST serviceERRest - Designing a good REST service
ERRest - Designing a good REST service
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntity
 

Andere mochten auch

Проектирование графических интерфейсов лекция 7
Проектирование графических интерфейсов лекция 7Проектирование графических интерфейсов лекция 7
Проектирование графических интерфейсов лекция 7
Technopark
 
Бизнес и системный анализ весна 2013 лекция 3
Бизнес и системный анализ весна 2013 лекция 3Бизнес и системный анализ весна 2013 лекция 3
Бизнес и системный анализ весна 2013 лекция 3
Technopark
 
Проектирование графических интерфейсов лекция 3
Проектирование графических интерфейсов лекция 3Проектирование графических интерфейсов лекция 3
Проектирование графических интерфейсов лекция 3
Technopark
 
СУБД осень 2012 Лекция 2
СУБД осень 2012 Лекция 2СУБД осень 2012 Лекция 2
СУБД осень 2012 Лекция 2
Technopark
 
Проектирование интерфейсов - NUI
Проектирование интерфейсов - NUIПроектирование интерфейсов - NUI
Проектирование интерфейсов - NUI
Technopark
 
HighLoad весна 2014 лекция 3
HighLoad весна 2014 лекция 3HighLoad весна 2014 лекция 3
HighLoad весна 2014 лекция 3
Technopark
 
Highload осень 2012 лекция 5
Highload осень 2012 лекция 5Highload осень 2012 лекция 5
Highload осень 2012 лекция 5
Technopark
 
Тестирование осень 2013 лекция 3
Тестирование осень 2013 лекция 3Тестирование осень 2013 лекция 3
Тестирование осень 2013 лекция 3
Technopark
 

Andere mochten auch (9)

Проектирование графических интерфейсов лекция 7
Проектирование графических интерфейсов лекция 7Проектирование графических интерфейсов лекция 7
Проектирование графических интерфейсов лекция 7
 
Бизнес и системный анализ весна 2013 лекция 3
Бизнес и системный анализ весна 2013 лекция 3Бизнес и системный анализ весна 2013 лекция 3
Бизнес и системный анализ весна 2013 лекция 3
 
Проектирование графических интерфейсов лекция 3
Проектирование графических интерфейсов лекция 3Проектирование графических интерфейсов лекция 3
Проектирование графических интерфейсов лекция 3
 
СУБД осень 2012 Лекция 2
СУБД осень 2012 Лекция 2СУБД осень 2012 Лекция 2
СУБД осень 2012 Лекция 2
 
Проектирование интерфейсов - NUI
Проектирование интерфейсов - NUIПроектирование интерфейсов - NUI
Проектирование интерфейсов - NUI
 
HighLoad весна 2014 лекция 3
HighLoad весна 2014 лекция 3HighLoad весна 2014 лекция 3
HighLoad весна 2014 лекция 3
 
Highload осень 2012 лекция 5
Highload осень 2012 лекция 5Highload осень 2012 лекция 5
Highload осень 2012 лекция 5
 
Тестирование осень 2013 лекция 3
Тестирование осень 2013 лекция 3Тестирование осень 2013 лекция 3
Тестирование осень 2013 лекция 3
 
Java осень 2014 занятие 7
Java осень 2014 занятие 7Java осень 2014 занятие 7
Java осень 2014 занятие 7
 

Ähnlich wie Web осень 2012 лекция 6

Web весна 2013 лекция 7
Web весна 2013 лекция 7Web весна 2013 лекция 7
Web весна 2013 лекция 7
Technopark
 
Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)
Leonardo Soto
 
用Tornado开发RESTful API运用
用Tornado开发RESTful API运用用Tornado开发RESTful API运用
用Tornado开发RESTful API运用
Felinx Lee
 
Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Django
fool2nd
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
 
Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)
Leonardo Soto
 
Gail villanueva add muscle to your wordpress site
Gail villanueva   add muscle to your wordpress siteGail villanueva   add muscle to your wordpress site
Gail villanueva add muscle to your wordpress site
references
 
Building a Portfolio With Custom Post Types
Building a Portfolio With Custom Post TypesBuilding a Portfolio With Custom Post Types
Building a Portfolio With Custom Post Types
Alex Blackie
 

Ähnlich wie Web осень 2012 лекция 6 (20)

Web весна 2013 лекция 7
Web весна 2013 лекция 7Web весна 2013 лекция 7
Web весна 2013 лекция 7
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4
 
The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196
 
The Ring programming language version 1.5.3 book - Part 40 of 184
The Ring programming language version 1.5.3 book - Part 40 of 184The Ring programming language version 1.5.3 book - Part 40 of 184
The Ring programming language version 1.5.3 book - Part 40 of 184
 
The Ring programming language version 1.10 book - Part 50 of 212
The Ring programming language version 1.10 book - Part 50 of 212The Ring programming language version 1.10 book - Part 50 of 212
The Ring programming language version 1.10 book - Part 50 of 212
 
Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)
 
用Tornado开发RESTful API运用
用Tornado开发RESTful API运用用Tornado开发RESTful API运用
用Tornado开发RESTful API运用
 
Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Django
 
Django
DjangoDjango
Django
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
 
Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)
 
Gail villanueva add muscle to your wordpress site
Gail villanueva   add muscle to your wordpress siteGail villanueva   add muscle to your wordpress site
Gail villanueva add muscle to your wordpress site
 
Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4
 
Play!ng with scala
Play!ng with scalaPlay!ng with scala
Play!ng with scala
 
Building a Portfolio With Custom Post Types
Building a Portfolio With Custom Post TypesBuilding a Portfolio With Custom Post Types
Building a Portfolio With Custom Post Types
 
The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31
 
The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
 
Requery overview
Requery overviewRequery overview
Requery overview
 
The Ring programming language version 1.6 book - Part 46 of 189
The Ring programming language version 1.6 book - Part 46 of 189The Ring programming language version 1.6 book - Part 46 of 189
The Ring programming language version 1.6 book - Part 46 of 189
 

Mehr von Technopark

СУБД 2013 Лекция №8 "Конфигурирование базы данных"
СУБД 2013 Лекция №8 "Конфигурирование базы данных"СУБД 2013 Лекция №8 "Конфигурирование базы данных"
СУБД 2013 Лекция №8 "Конфигурирование базы данных"
Technopark
 
СУБД 2013 Лекция №7 "Оптимизация запросов и индексирование"
СУБД 2013 Лекция №7 "Оптимизация запросов и индексирование"СУБД 2013 Лекция №7 "Оптимизация запросов и индексирование"
СУБД 2013 Лекция №7 "Оптимизация запросов и индексирование"
Technopark
 
СУБД 2013 Лекция №6 "Профилирование запросов. Сложноструктурированные SQL-зап...
СУБД 2013 Лекция №6 "Профилирование запросов. Сложноструктурированные SQL-зап...СУБД 2013 Лекция №6 "Профилирование запросов. Сложноструктурированные SQL-зап...
СУБД 2013 Лекция №6 "Профилирование запросов. Сложноструктурированные SQL-зап...
Technopark
 

Mehr von Technopark (20)

Лекция 11. Вычислительная модель Pregel
Лекция 11. Вычислительная модель PregelЛекция 11. Вычислительная модель Pregel
Лекция 11. Вычислительная модель Pregel
 
Лекция 14. Hadoop в Поиске Mail.Ru
Лекция 14. Hadoop в Поиске Mail.RuЛекция 14. Hadoop в Поиске Mail.Ru
Лекция 14. Hadoop в Поиске Mail.Ru
 
Лекция 13. YARN
Лекция 13. YARNЛекция 13. YARN
Лекция 13. YARN
 
Лекция 12. Spark
Лекция 12. SparkЛекция 12. Spark
Лекция 12. Spark
 
Лекция 10. Apache Mahout
Лекция 10. Apache MahoutЛекция 10. Apache Mahout
Лекция 10. Apache Mahout
 
Лекция 9. ZooKeeper
Лекция 9. ZooKeeperЛекция 9. ZooKeeper
Лекция 9. ZooKeeper
 
Лекция 7. Введение в Pig и Hive
Лекция 7. Введение в Pig и HiveЛекция 7. Введение в Pig и Hive
Лекция 7. Введение в Pig и Hive
 
Лекция 6. MapReduce в Hadoop (графы)
Лекция 6. MapReduce в Hadoop (графы)Лекция 6. MapReduce в Hadoop (графы)
Лекция 6. MapReduce в Hadoop (графы)
 
Лекция 5. MapReduce в Hadoop (алгоритмы)
Лекция 5. MapReduce в Hadoop (алгоритмы)Лекция 5. MapReduce в Hadoop (алгоритмы)
Лекция 5. MapReduce в Hadoop (алгоритмы)
 
Лекция 4. MapReduce в Hadoop (введение)
Лекция 4. MapReduce в Hadoop (введение)Лекция 4. MapReduce в Hadoop (введение)
Лекция 4. MapReduce в Hadoop (введение)
 
Лекция 3. Распределённая файловая система HDFS
Лекция 3. Распределённая файловая система HDFSЛекция 3. Распределённая файловая система HDFS
Лекция 3. Распределённая файловая система HDFS
 
Лекция 2. Основы Hadoop
Лекция 2. Основы HadoopЛекция 2. Основы Hadoop
Лекция 2. Основы Hadoop
 
Лекция 1. Введение в Big Data и MapReduce
Лекция 1. Введение в Big Data и MapReduceЛекция 1. Введение в Big Data и MapReduce
Лекция 1. Введение в Big Data и MapReduce
 
СУБД 2013 Лекция №10 "Нереляционное решение в области баз данных — NoSQL"
СУБД 2013 Лекция №10 "Нереляционное решение в области баз данных — NoSQL"СУБД 2013 Лекция №10 "Нереляционное решение в области баз данных — NoSQL"
СУБД 2013 Лекция №10 "Нереляционное решение в области баз данных — NoSQL"
 
СУБД 2013 Лекция №10 "Нереляционное решение в области баз данных — NoSQL" Час...
СУБД 2013 Лекция №10 "Нереляционное решение в области баз данных — NoSQL" Час...СУБД 2013 Лекция №10 "Нереляционное решение в области баз данных — NoSQL" Час...
СУБД 2013 Лекция №10 "Нереляционное решение в области баз данных — NoSQL" Час...
 
СУБД 2013 Лекция №9 "Безопасность баз данных"
СУБД 2013 Лекция №9 "Безопасность баз данных"СУБД 2013 Лекция №9 "Безопасность баз данных"
СУБД 2013 Лекция №9 "Безопасность баз данных"
 
СУБД 2013 Лекция №8 "Конфигурирование базы данных"
СУБД 2013 Лекция №8 "Конфигурирование базы данных"СУБД 2013 Лекция №8 "Конфигурирование базы данных"
СУБД 2013 Лекция №8 "Конфигурирование базы данных"
 
СУБД 2013 Лекция №7 "Оптимизация запросов и индексирование"
СУБД 2013 Лекция №7 "Оптимизация запросов и индексирование"СУБД 2013 Лекция №7 "Оптимизация запросов и индексирование"
СУБД 2013 Лекция №7 "Оптимизация запросов и индексирование"
 
СУБД 2013 Лекция №5 "Определение узких мест"
СУБД 2013 Лекция №5 "Определение узких мест"СУБД 2013 Лекция №5 "Определение узких мест"
СУБД 2013 Лекция №5 "Определение узких мест"
 
СУБД 2013 Лекция №6 "Профилирование запросов. Сложноструктурированные SQL-зап...
СУБД 2013 Лекция №6 "Профилирование запросов. Сложноструктурированные SQL-зап...СУБД 2013 Лекция №6 "Профилирование запросов. Сложноструктурированные SQL-зап...
СУБД 2013 Лекция №6 "Профилирование запросов. Сложноструктурированные SQL-зап...
 

Kürzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 

Web осень 2012 лекция 6

  • 1.
  • 3. def application(environ, start_response): status = '200 OK' output = 'Hello World!' response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))] start_response(status, response_headers) return [output] WSGIScriptAlias / /path/to/megasite/mysite.wsgi
  • 5. from cgi import parse_qs, escape index_html = """<html>...</html>""" about_html = """<html>...</html>""" contact_html = """<html>...</html>""" def application(environ, start_response): # Returns a dictionary containing lists as values. d = parse_qs(environ['QUERY_STRING']) # In this idiom you must issue a list containing a default value. page = d.get('page', [''])[0] # Returns the first page value. # Always escape user input to avoid script injection page = escape(page) if page == 'about': response_body = about_html elif page == 'contact': response_body = contact_html else: response_body = index_html status = '200 OK' response_headers = [('Content-Type', 'text/html'), ('Content-Length', str(len(response_body)))] start_response(status, response_headers) return [response_body]
  • 7. app = Flask(__name__) @app.route('/') def index_page(): db = get_db() cur = db.execute('select title, text from entries order by id desc') entries = cur.fetchall() return render_template('show_entries.html', entries=entries) @app.route('/contact/') def contact_page(): return render_template('contact_page.html')
  • 9. Model-view-controller – схема использования нескольких шаблонов проектирования, с помощью которых модель данных приложения, пользовательский интерфейс и взаимодействие с пользователем разделены на три отдельных компонента так, что модификация одного из компонентов оказывает минимальное воздействие на остальные.
  • 10.
  • 12.
  • 13.
  • 14.
  • 18.
  • 20.
  • 22.
  • 23. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'blog', 'USER': 'root', 'PASSWORD': '1', 'HOST': '', 'PORT': '', } }
  • 27. from django.db import models import datetime class Category(models.Model): title = models.CharField(max_length=255) description = models.TextField(blank=True) def __unicode__(self): return self.title @models.permalink def get_absolute_url(self): return ('category_detail', (self.pk,))
  • 28. class Post(models.Model): title = models.CharField(max_length=255) content = models.TextField() category = models.ForeignKey(Category) creation_date = models.DateTimeField(default=datetime.datetime.now) def previous_post(self): """Return the previous entry""" def next_post(self): """Return the next entry""" def __unicode__(self): return self.title @models.permalink def get_absolute_url(self): return ('post_detail', (self.pk,)) class Meta: ordering = ['-creation_date']
  • 29.
  • 30.
  • 31.
  • 32. >>> from blog.models import Category, Post >>> Category.objects.all() [] >>> c = Category(title="Python") >>> c.save() >>> c.id 1 >>> c.title="About Python" >>> c.save() >>> Category.objects.all() [<Category: About Python>]
  • 33. >>> Category.objects.filter(id=1) [<Category: About Python>] >>> c = Category.objects.get(id=1) <Category: About Python> >>> c.post_set.all() [] >>> c.post_set.create(title="New post", content="Many words") <Post: New post> >>> c.post_set.count() 1 >>> c.delete()
  • 35. def post_list(request): object_list = Post.objects.all() return render( request, 'blog/post_list.html', {'object_list': object_list} ) def post_detail(request, pk): try: object = Post.objects.get(pk=pk) except Post.DoesNotExist: raise Http404 return render( request, 'blog/post_detail.html', {'object': object} )
  • 36. def category(request, pk): cat = get_object_or_404(Category, pk=pk) post_list = Post.objects.filter(category=cat) return render(request, 'blog/category.html', { 'category': cat, 'post_list' : post_list })
  • 37. from django.conf.urls import patterns, url urlpatterns = patterns('blog.views', (r'^$', 'post_list'), url(r'^post/(?P<pk>d+)/$', 'post_detail', name='post_detail'), url(r'^category/(?P<pk>d+)/$', 'category', name='category_detail'), )
  • 39. <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Блог</title> </head> <body> <h1>Мой блог</h1> {% block content %}{% endblock %} </body> </html>
  • 40. {% extends "base.html" %} {% block content %} <ul> {% for object in object_list %} <li><a href="{{ object.get_absolute_url }}">{{ object }}</a> {{ object.created_date|date:"d.m.Y" }}</li> {% endfor %} </ul> {% endblock %}
  • 41. {% extends "base.html" %} {% block content %} <h2>{{ object }}</h2> <p><small>{{ object.creation_date }} <a href="{{ object.category.get_absolute_url}}">{{ object.category }}</a></p> <div>{{ object.content }}</div> {% endblock %}
  • 42. {% extends "base.html" %} {% block content %} <h2>{{ category }}</h2> <ul> {% for object in post_list %} <li><a href="{{ object.get_absolute_url}}">{{ object }}</a></li> {% endfor %} </ul> {% endblock %}
  • 43. from django import forms class ContactForm(forms.Form): email = forms.EmailField(label=u'Ваш e-mail', max_length=100) message = forms.CharField(label=u'Сообщение', widget=forms.Textarea)
  • 44. from blog.forms import ContactForm from django.core.mail import send_mail from django.http import HttpResponseRedirect def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject = u'Сообщение с блога' message = form.cleaned_data['message'] sender = form.cleaned_data['email'] recipients = ['a.bekbulatov@corp.mail.ru'] send_mail(subject, message, sender, recipients) return HttpResponseRedirect('/') else: form = ContactForm() return render(request, 'blog/contact.html', { 'form': form })
  • 45. urlpatterns = patterns('blog.views', (r'^$', 'post_list'), url(r'^post/(?P<pk>d+)/$', 'post_detail', name='post_detail'), url(r'^category/(?P<pk>d+)/$', 'category', name='category_detail'), (r'^contacts/$', 'contact'), )
  • 46. {% extends "base.html" %} {% block content %} <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Отправить" /> </form> {% endblock %}
  • 47. from django import template from blog.models import Post register = template.Library() @register.inclusion_tag('blog/tags/last_posts.html') def last_posts(): return {'post_list': Post.objects.all()[:5]}
  • 48. <ul> {% for object in post_list %} <li><a href="{{ object.get_absolute_url}}">{{ object }}</a></li> {% endfor %} </ul> {% load blog_tags %} {% last_posts %}