SlideShare a Scribd company logo
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
Technopark
 
KEY
Scala on Your Phone
Michael Galpin
 
PDF
Advanced Django
Simon Willison
 
PDF
PofEAA and SQLAlchemy
Inada Naoki
 
KEY
Symfony2 Building on Alpha / Beta technology
Daniel Knell
 
PDF
ERRest
WO Community
 
PDF
Django tutorial 2009
Ferenc Szalai
 
PDF
Django (Web Konferencia 2009)
Szilveszter Farkas
 
Web осень 2012 лекция 6
Technopark
 
Scala on Your Phone
Michael Galpin
 
Advanced Django
Simon Willison
 
PofEAA and SQLAlchemy
Inada Naoki
 
Symfony2 Building on Alpha / Beta technology
Daniel Knell
 
ERRest
WO Community
 
Django tutorial 2009
Ferenc Szalai
 
Django (Web Konferencia 2009)
Szilveszter Farkas
 

What's hot (20)

ODP
Patterns for slick database applications
Skills Matter
 
PDF
Building Real Time Systems on MongoDB Using the Oplog at Stripe
MongoDB
 
PPTX
Cfml features modern coding into the box 2018
Ortus Solutions, Corp
 
PDF
ERRest in Depth
WO Community
 
PDF
Phoenix + Reactで 社内システムを 密かに作ってる
Takahiro Kobaru
 
PPT
PHP webboard
tumetr1
 
PPT
PHP cart
tumetr1
 
PDF
Leveraging Symfony2 Forms
Bernhard Schussek
 
PDF
Web2py Code Lab
Colin Su
 
KEY
テストデータどうしてますか?
Yuki Shibazaki
 
PPTX
Web осень 2012 лекция 7
Technopark
 
PDF
How te bring common UI patterns to ADF
Getting value from IoT, Integration and Data Analytics
 
PDF
Web2py tutorial to create db driven application.
fRui Apps
 
PDF
Everything you always wanted to know about forms* *but were afraid to ask
Andrea Giuliano
 
PDF
Everything About PowerShell
Gaetano Causio
 
PDF
ERRest - The Next Steps
WO Community
 
KEY
Introducing CakeEntity
Basuke Suzuki
 
KEY
Unit testing with zend framework PHPBenelux
Michelangelo van Dam
 
PPTX
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
Sencha
 
PPTX
jQuery from the very beginning
Anis Ahmad
 
Patterns for slick database applications
Skills Matter
 
Building Real Time Systems on MongoDB Using the Oplog at Stripe
MongoDB
 
Cfml features modern coding into the box 2018
Ortus Solutions, Corp
 
ERRest in Depth
WO Community
 
Phoenix + Reactで 社内システムを 密かに作ってる
Takahiro Kobaru
 
PHP webboard
tumetr1
 
PHP cart
tumetr1
 
Leveraging Symfony2 Forms
Bernhard Schussek
 
Web2py Code Lab
Colin Su
 
テストデータどうしてますか?
Yuki Shibazaki
 
Web осень 2012 лекция 7
Technopark
 
How te bring common UI patterns to ADF
Getting value from IoT, Integration and Data Analytics
 
Web2py tutorial to create db driven application.
fRui Apps
 
Everything you always wanted to know about forms* *but were afraid to ask
Andrea Giuliano
 
Everything About PowerShell
Gaetano Causio
 
ERRest - The Next Steps
WO Community
 
Introducing CakeEntity
Basuke Suzuki
 
Unit testing with zend framework PHPBenelux
Michelangelo van Dam
 
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
Sencha
 
jQuery from the very beginning
Anis Ahmad
 
Ad

Viewers also liked (15)

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

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

PPTX
Python Code Camp for Professionals 4/4
DEVCON
 
PDF
The Ring programming language version 1.7 book - Part 48 of 196
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.5.3 book - Part 40 of 184
Mahmoud Samir Fayed
 
PPT
Django
Kangjin Jun
 
KEY
Jython: Python para la plataforma Java (EL2009)
Leonardo Soto
 
PDF
The Ring programming language version 1.10 book - Part 50 of 212
Mahmoud Samir Fayed
 
PDF
Gae Meets Django
fool2nd
 
PDF
用Tornado开发RESTful API运用
Felinx Lee
 
PPTX
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
 
KEY
Jython: Python para la plataforma Java (JRSL 09)
Leonardo Soto
 
PDF
Gail villanueva add muscle to your wordpress site
references
 
PPTX
Python Code Camp for Professionals 1/4
DEVCON
 
PPT
Play!ng with scala
Siarzh Miadzvedzeu
 
PDF
Building a Portfolio With Custom Post Types
Alex Blackie
 
PDF
The Ring programming language version 1.8 book - Part 50 of 202
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.5 book - Part 8 of 31
Mahmoud Samir Fayed
 
PDF
jQuery Essentials
Marc Grabanski
 
PDF
The Ring programming language version 1.5.1 book - Part 43 of 180
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.6 book - Part 46 of 189
Mahmoud Samir Fayed
 
PDF
Requery overview
Sunghyouk Bae
 
Python Code Camp for Professionals 4/4
DEVCON
 
The Ring programming language version 1.7 book - Part 48 of 196
Mahmoud Samir Fayed
 
The Ring programming language version 1.5.3 book - Part 40 of 184
Mahmoud Samir Fayed
 
Django
Kangjin Jun
 
Jython: Python para la plataforma Java (EL2009)
Leonardo Soto
 
The Ring programming language version 1.10 book - Part 50 of 212
Mahmoud Samir Fayed
 
Gae Meets Django
fool2nd
 
用Tornado开发RESTful API运用
Felinx Lee
 
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
 
Jython: Python para la plataforma Java (JRSL 09)
Leonardo Soto
 
Gail villanueva add muscle to your wordpress site
references
 
Python Code Camp for Professionals 1/4
DEVCON
 
Play!ng with scala
Siarzh Miadzvedzeu
 
Building a Portfolio With Custom Post Types
Alex Blackie
 
The Ring programming language version 1.8 book - Part 50 of 202
Mahmoud Samir Fayed
 
The Ring programming language version 1.5 book - Part 8 of 31
Mahmoud Samir Fayed
 
jQuery Essentials
Marc Grabanski
 
The Ring programming language version 1.5.1 book - Part 43 of 180
Mahmoud Samir Fayed
 
The Ring programming language version 1.6 book - Part 46 of 189
Mahmoud Samir Fayed
 
Requery overview
Sunghyouk Bae
 

More from Technopark (20)

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

Recently uploaded (20)

PDF
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
The Future of Artificial Intelligence (AI)
Mukul
 
PDF
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PPTX
Simple and concise overview about Quantum computing..pptx
mughal641
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PPTX
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
PDF
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PDF
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
PDF
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
Software Development Methodologies in 2025
KodekX
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
The Future of Artificial Intelligence (AI)
Mukul
 
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
Simple and concise overview about Quantum computing..pptx
mughal641
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Software Development Methodologies in 2025
KodekX
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 

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 = ['[email protected]'] 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 %}