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

51

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

Page 1: Web осень 2012 лекция 6
Page 2: Web осень 2012 лекция 6

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

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

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

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

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]

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

Page 7: Web осень 2012 лекция 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')

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

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

Model-view-controller – схема использования нескольких шаблонов

проектирования, с помощью которых модель данных приложения,

пользовательский интерфейс и взаимодействие с пользователем

разделены на три отдельных компонента так, что модификация

одного из компонентов оказывает минимальное воздействие на

остальные.

Page 10: Web осень 2012 лекция 6
Page 11: Web осень 2012 лекция 6

Page 12: Web осень 2012 лекция 6
Page 13: Web осень 2012 лекция 6
Page 14: Web осень 2012 лекция 6
Page 15: Web осень 2012 лекция 6

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

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

Page 18: Web осень 2012 лекция 6
Page 19: Web осень 2012 лекция 6

Page 20: Web осень 2012 лекция 6
Page 21: Web осень 2012 лекция 6

myblog/

manage.py

myblog/

__init__.py

settings.py

urls.py

wsgi.py

Page 22: Web осень 2012 лекция 6
Page 23: Web осень 2012 лекция 6

DATABASES = {

'default': {

'ENGINE': 'django.db.backends.mysql',

'NAME': 'blog',

'USER': 'root',

'PASSWORD': '1',

'HOST': '',

'PORT': '',

}

}

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

blog/

__init__.py

models.py

tests.py

views.py

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

INSTALLED_APPS = (

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.sites',

'django.contrib.messages',

'django.contrib.staticfiles',

'django.contrib.admin',

'blog',

)

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

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

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,))

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

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

Page 29: Web осень 2012 лекция 6
Page 30: Web осень 2012 лекция 6
Page 31: Web осень 2012 лекция 6
Page 32: Web осень 2012 лекция 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>]

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

>>> 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()

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

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

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}

)

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

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

})

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

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'),

)

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

import os

def rel(*x):

return

os.path.join(os.path.abspath(os.path.dirname(__file_

_)), * x)

TEMPLATE_DIRS = (

rel('../templates'),

)

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

<!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>

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

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

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

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

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

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

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

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)

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

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

})

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

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'),

)

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

{% extends "base.html" %}

{% block content %}

<form action="" method="post">

{% csrf_token %}

{{ form.as_p }}

<input type="submit" value="Отправить" />

</form>

{% endblock %}

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

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

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

<ul>

{% for object in post_list %}

<li><a href="{{ object.get_absolute_url}}">{{

object }}</a></li>

{% endfor %}

</ul>

{% load blog_tags %}

{% last_posts %}

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

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

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