Web весна 2013 лекция 6
•

•
•
•
WSGIScriptAlias / /path/to/megasite/mysite.wsgi

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]
•

•
•
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 – схема использования нескольких шаблонов
проектирования, с помощью которых модель данных приложения,
пользовательский интерфейс и взаимодействие с пользователем
разделены на три отдельных компонента так, что модификация
одного из компонентов оказывает минимальное воздействие на

остальные.
Web весна 2013 лекция 6
•

•
•
•
•
Web весна 2013 лекция 6
Web весна 2013 лекция 6
Web весна 2013 лекция 6
•

•
•
•
•
•

•
•
•
•

•
•
•
•
Web весна 2013 лекция 6
•

•
•
•
•
•
•
•
Web весна 2013 лекция 6
myblog/
manage.py
myblog/
__init__.py
settings.py

urls.py
wsgi.py
Web весна 2013 лекция 6
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']
Web весна 2013 лекция 6
Web весна 2013 лекция 6
Web весна 2013 лекция 6
>>> 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 весна 2013 лекция 6

More Related Content

PPTX
Web осень 2012 лекция 6
KEY
Scala on Your Phone
PDF
Advanced Django
PDF
PofEAA and SQLAlchemy
KEY
Symfony2 Building on Alpha / Beta technology
PDF
ERRest
PDF
Django tutorial 2009
PDF
Django (Web Konferencia 2009)
Web осень 2012 лекция 6
Scala on Your Phone
Advanced Django
PofEAA and SQLAlchemy
Symfony2 Building on Alpha / Beta technology
ERRest
Django tutorial 2009
Django (Web Konferencia 2009)

What's hot (20)

ODP
Patterns for slick database applications
PDF
Building Real Time Systems on MongoDB Using the Oplog at Stripe
PPTX
Cfml features modern coding into the box 2018
PDF
ERRest in Depth
PDF
Phoenix + Reactで 社内システムを 密かに作ってる
PPT
PHP webboard
PPT
PHP cart
PDF
Leveraging Symfony2 Forms
PDF
Web2py Code Lab
KEY
テストデータどうしてますか?
PPTX
Web осень 2012 лекция 7
PDF
How te bring common UI patterns to ADF
PDF
Web2py tutorial to create db driven application.
PDF
Everything you always wanted to know about forms* *but were afraid to ask
PDF
Everything About PowerShell
PDF
ERRest - The Next Steps
KEY
Introducing CakeEntity
KEY
Unit testing with zend framework PHPBenelux
PPTX
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
PPTX
jQuery from the very beginning
Patterns for slick database applications
Building Real Time Systems on MongoDB Using the Oplog at Stripe
Cfml features modern coding into the box 2018
ERRest in Depth
Phoenix + Reactで 社内システムを 密かに作ってる
PHP webboard
PHP cart
Leveraging Symfony2 Forms
Web2py Code Lab
テストデータどうしてますか?
Web осень 2012 лекция 7
How te bring common UI patterns to ADF
Web2py tutorial to create db driven application.
Everything you always wanted to know about forms* *but were afraid to ask
Everything About PowerShell
ERRest - The Next Steps
Introducing CakeEntity
Unit testing with zend framework PHPBenelux
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
jQuery from the very beginning
Ad

Viewers also liked (15)

PPT
Web весна 2013 лекция 8
PPT
Web весна 2013 лекция 3
PPT
Web весна 2013 лекция 4
PPT
Web весна 2013 лекция 9
PPT
Web весна 2013 лекция 2
PDF
Михаил Давыдов: JavaScript. Базовые знания
PPTX
Web осень 2013 лекция 9
PDF
Web осень 2013 лекция 3
PPTX
Web осень 2013 лекция 7
PPTX
Web осень 2013 лекция 5
PPT
Web весна 2013 лекция 5
PPTX
Web весна 2013 лекция 7
PPTX
СУБД 2013 Лекция №5 "Определение узких мест"
PDF
Михаил Давыдов — JavaScript: События
PDF
Лекция 11. Вычислительная модель Pregel
Web весна 2013 лекция 8
Web весна 2013 лекция 3
Web весна 2013 лекция 4
Web весна 2013 лекция 9
Web весна 2013 лекция 2
Михаил Давыдов: JavaScript. Базовые знания
Web осень 2013 лекция 9
Web осень 2013 лекция 3
Web осень 2013 лекция 7
Web осень 2013 лекция 5
Web весна 2013 лекция 5
Web весна 2013 лекция 7
СУБД 2013 Лекция №5 "Определение узких мест"
Михаил Давыдов — JavaScript: События
Лекция 11. Вычислительная модель Pregel
Ad

Similar to Web весна 2013 лекция 6 (20)

PPTX
Python Code Camp for Professionals 4/4
PDF
The Ring programming language version 1.7 book - Part 48 of 196
PDF
The Ring programming language version 1.5.3 book - Part 40 of 184
PPT
Django
KEY
Jython: Python para la plataforma Java (EL2009)
PDF
The Ring programming language version 1.10 book - Part 50 of 212
PDF
Gae Meets Django
PDF
用Tornado开发RESTful API运用
PPTX
Dev Jumpstart: Build Your First App with MongoDB
KEY
Jython: Python para la plataforma Java (JRSL 09)
PDF
Gail villanueva add muscle to your wordpress site
PPTX
Python Code Camp for Professionals 1/4
PPT
Play!ng with scala
PDF
Building a Portfolio With Custom Post Types
PDF
The Ring programming language version 1.8 book - Part 50 of 202
PDF
The Ring programming language version 1.5 book - Part 8 of 31
PDF
jQuery Essentials
PDF
The Ring programming language version 1.5.1 book - Part 43 of 180
PDF
The Ring programming language version 1.6 book - Part 46 of 189
PDF
Requery overview
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.5.3 book - Part 40 of 184
Django
Jython: Python para la plataforma Java (EL2009)
The Ring programming language version 1.10 book - Part 50 of 212
Gae Meets Django
用Tornado开发RESTful API运用
Dev Jumpstart: Build Your First App with MongoDB
Jython: Python para la plataforma Java (JRSL 09)
Gail villanueva add muscle to your wordpress site
Python Code Camp for Professionals 1/4
Play!ng with scala
Building a Portfolio With Custom Post Types
The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.5 book - Part 8 of 31
jQuery Essentials
The Ring programming language version 1.5.1 book - Part 43 of 180
The Ring programming language version 1.6 book - Part 46 of 189
Requery overview

More from Technopark (20)

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

Recently uploaded (20)

PDF
Taming the Chaos: How to Turn Unstructured Data into Decisions
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Five Habits of High-Impact Board Members
PDF
A novel scalable deep ensemble learning framework for big data classification...
PPTX
Final SEM Unit 1 for mit wpu at pune .pptx
PDF
Developing a website for English-speaking practice to English as a foreign la...
DOCX
search engine optimization ppt fir known well about this
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
Architecture types and enterprise applications.pdf
PDF
A contest of sentiment analysis: k-nearest neighbor versus neural network
PDF
STKI Israel Market Study 2025 version august
PPT
Geologic Time for studying geology for geologist
PDF
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
PDF
Unlock new opportunities with location data.pdf
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PPTX
observCloud-Native Containerability and monitoring.pptx
PDF
DP Operators-handbook-extract for the Mautical Institute
PDF
Hybrid model detection and classification of lung cancer
PPTX
The various Industrial Revolutions .pptx
PPT
What is a Computer? Input Devices /output devices
Taming the Chaos: How to Turn Unstructured Data into Decisions
Assigned Numbers - 2025 - Bluetooth® Document
Five Habits of High-Impact Board Members
A novel scalable deep ensemble learning framework for big data classification...
Final SEM Unit 1 for mit wpu at pune .pptx
Developing a website for English-speaking practice to English as a foreign la...
search engine optimization ppt fir known well about this
Group 1 Presentation -Planning and Decision Making .pptx
Architecture types and enterprise applications.pdf
A contest of sentiment analysis: k-nearest neighbor versus neural network
STKI Israel Market Study 2025 version august
Geologic Time for studying geology for geologist
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
Unlock new opportunities with location data.pdf
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
observCloud-Native Containerability and monitoring.pptx
DP Operators-handbook-extract for the Mautical Institute
Hybrid model detection and classification of lung cancer
The various Industrial Revolutions .pptx
What is a Computer? Input Devices /output devices

Web весна 2013 лекция 6

  • 3. WSGIScriptAlias / /path/to/megasite/mysite.wsgi 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]
  • 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 – схема использования нескольких шаблонов проектирования, с помощью которых модель данных приложения, пользовательский интерфейс и взаимодействие с пользователем разделены на три отдельных компонента так, что модификация одного из компонентов оказывает минимальное воздействие на остальные.
  • 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']
  • 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 %}