Web осень 2012 лекция 6
Upcoming SlideShare
Loading in...5
×
 

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

on

  • 263 views

 

Statistics

Views

Total Views
263
Views on SlideShare
260
Embed Views
3

Actions

Likes
0
Downloads
1
Comments
0

1 Embed 3

http://tp.mail.ru 3

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

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

  • • • • •
  • 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 %}
  • • • • • •
  • • • • • •