0
•
•
•
•
def application(environ, start_response):
status = '200 OK'
output = 'Hello World!'
response_headers = [('Content-type', '...
•
•
•
from cgi import parse_qs, escape
index_html = """<html>...</html>"""
about_html = """<html>...</html>"""
contact_html = ""...
•
•
•
•
•
app = Flask(__name__)
@app.route('/')
def index_page():
db = get_db()
cur = db.execute('select title, text from entries or...
•
•
•
•
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': ...
blog/
__init__.py
models.py
tests.py
views.py
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites'...
•
•
•
•
from django.db import models
import datetime
class Category(models.Model):
title = models.CharField(max_length=255)
descri...
class Post(models.Model):
title = models.CharField(max_length=255)
content = models.TextField()
category = models.ForeignK...
>>> from blog.models import Category, Post
>>> Category.objects.all()
[]
>>> c = Category(title="Python")
>>> c.save()
>>>...
>>> Category.objects.filter(id=1)
[<Category: About Python>]
>>> c = Category.objects.get(id=1)
<Category: About Python>
>...
•
•
•
def post_list(request):
object_list = Post.objects.all()
return render(
request, 'blog/post_list.html',
{'object_list': ob...
def category(request, pk):
cat = get_object_or_404(Category, pk=pk)
post_list = Post.objects.filter(category=cat)
return r...
from django.conf.urls import patterns, url
urlpatterns = patterns('blog.views',
(r'^$', 'post_list'),
url(r'^post/(?P<pk>d...
import os
def rel(*x):
return
os.path.join(os.path.abspath(os.path.dirname(__file_
_)), * x)
TEMPLATE_DIRS = (
rel('../tem...
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=utf-8">
<title>Блог</title>
</he...
{% extends "base.html" %}
{% block content %}
<ul>
{% for object in object_list %}
<li><a href="{{ object.get_absolute_url...
{% extends "base.html" %}
{% block content %}
<h2>{{ object }}</h2>
<p><small>{{ object.creation_date }} <a
href="{{ objec...
{% extends "base.html" %}
{% block content %}
<h2>{{ category }}</h2>
<ul>
{% for object in post_list %}
<li><a href="{{
o...
from django import forms
class ContactForm(forms.Form):
email = forms.EmailField(label=u'Ваш e-mail',
max_length=100)
mess...
from blog.forms import ContactForm
from django.core.mail import send_mail
from django.http import HttpResponseRedirect
def...
urlpatterns = patterns('blog.views',
(r'^$', 'post_list'),
url(r'^post/(?P<pk>d+)/$', 'post_detail',
name='post_detail'),
...
{% extends "base.html" %}
{% block content %}
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type=...
from django import template
from blog.models import Post
register = template.Library()
@register.inclusion_tag('blog/tags/...
<ul>
{% for object in post_list %}
<li><a href="{{ object.get_absolute_url}}">{{
object }}</a></li>
{% endfor %}
</ul>
{% ...
•
•
•
•
•
•
•
•
•
•
Web осень 2012 лекция 6
Web осень 2012 лекция 6
Web осень 2012 лекция 6
Web осень 2012 лекция 6
Web осень 2012 лекция 6
Web осень 2012 лекция 6
Web осень 2012 лекция 6
Web осень 2012 лекция 6
Web осень 2012 лекция 6
Web осень 2012 лекция 6
Web осень 2012 лекция 6
Web осень 2012 лекция 6
Upcoming SlideShare
Loading in...5
×

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

166

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
166
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
2
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

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

  1. 1. • • • •
  2. 2. 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
  3. 3. • • •
  4. 4. 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]
  5. 5. • • • • •
  6. 6. 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')
  7. 7. • • • •
  8. 8. Model-view-controller – схема использования нескольких шаблонов проектирования, с помощью которых модель данных приложения, пользовательский интерфейс и взаимодействие с пользователем разделены на три отдельных компонента так, что модификация одного из компонентов оказывает минимальное воздействие на остальные.
  9. 9. • • • • •
  10. 10. • • • • •
  11. 11. • • • •
  12. 12. • • • • •
  13. 13. • • • • • • • •
  14. 14. myblog/ manage.py myblog/ __init__.py settings.py urls.py wsgi.py
  15. 15. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'blog', 'USER': 'root', 'PASSWORD': '1', 'HOST': '', 'PORT': '', } }
  16. 16. blog/ __init__.py models.py tests.py views.py
  17. 17. INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'blog', )
  18. 18. • • • •
  19. 19. 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,))
  20. 20. 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']
  21. 21. >>> 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>]
  22. 22. >>> 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()
  23. 23. • • •
  24. 24. 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} )
  25. 25. 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 })
  26. 26. 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'), )
  27. 27. import os def rel(*x): return os.path.join(os.path.abspath(os.path.dirname(__file_ _)), * x) TEMPLATE_DIRS = ( rel('../templates'), )
  28. 28. <!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>
  29. 29. {% 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 %}
  30. 30. {% 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 %}
  31. 31. {% 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 %}
  32. 32. 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)
  33. 33. 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 })
  34. 34. 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'), )
  35. 35. {% extends "base.html" %} {% block content %} <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Отправить" /> </form> {% endblock %}
  36. 36. 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]}
  37. 37. <ul> {% for object in post_list %} <li><a href="{{ object.get_absolute_url}}">{{ object }}</a></li> {% endfor %} </ul> {% load blog_tags %} {% last_posts %}
  38. 38. • • • • •
  39. 39. • • • • •
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×