Upload
others
View
2
Download
0
Embed Size (px)
Citation preview
CE419 Web Programming
Session 13: Django Web Framework: Views
Review
• Model—Template—View architecture
Views and URLconfs
• Django has the concept of views to encapsulate the logic responsible for processing a user’s request and for returning the response.
• Comparison with the CGI example (random number generator).
Writing Views
• A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response.
from django.http import HttpResponse import datetime
def current_datetime(request): now = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % now return HttpResponse(html)
1
2
3
4
URLconfs
• Fire up the built-in web server!
• Where is my view?!
~/myblog $ python manage.py runserver
URLconfs (cont'd)
• Remember HTTP requests?
• We need a way to map a path to a view.
• When the user requests for a path, Django finds the corresponding view and executes it.
GET /now/ HTTP/1.1 Host: mail.ce.sharif.edu Referer: http://mail.ce.sharif.edu/ Content-Length: 125
URLconfs (cont'd)
• To hook a view function to a particular URL with Django, use a URLconf.
• A URLconf is like a table of contents for your Django-powered Web site.
• “For this URL, call this code, and for that URL, call that code.”
URLconfs (cont'd)
myblog/ ├── manage.py └── myblog ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py
from django.conf.urls import include, url from django.contrib import admin
urlpatterns = [ url(r'^now/$', 'posts.views.current_datetime'), url(r'^login/$', 'users.views.login'), url(r'^admin/', include(admin.site.urls)), ]
12 3
URLconfs (cont'd)
• What the URLconf searches against?
• The URLconf searches against the requested URL, as a normal Python string. This does not include GET or POST parameters, or the domain name.
http://www.example.com/myapp/?page=3
myapp/
URL Patterns
• Not are URLs are that simple.
• We can use Regular Expressions to capture these.
https://www.facebook.com/groups/390233697744819/ http://www.imdb.com/title/tt0816692/ https://twitter.com/Arsenal/status/107858262212358144 https://itunes.apple.com/us/genre/ios-business/id6000 http://www.last.fm/user/johndoe/now
^groups/(\d+)/$ ^title/tt(\d+)/$ ^(?P<username>\w+)/status/(?P<tweet_id>\d+)$
Let's see 'regular expressions' in action.
Showtime!
�11
Capture Values
• To capture a value from the URL, just put parenthesis around it.
from django.conf.urls import url
from . import views
urlpatterns = [ url(r'^articles/2003/$', views.special_case_2003), url(r'^articles/([0-9]{4})/$', views.year_archive), url(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive), url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', views.article_detail), ]
http://www.example.com/articles/2014/12/
month_archive(request, '2014', '12')
Capture Values (cont'd)
• The previous example used simple, non-named regular-expression groups (via parenthesis) to capture bits of the URL and pass them as positional arguments to a view.
• In more advanced usage, it’s possible to use named regular-expression groups to capture URL bits and pass them as keyword arguments to a view.
Capture Values (cont'd)
• In Python regular expressions, the syntax for named regular-expression groups is (?P<name>pattern)
• Captured arguments are always strings.
url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive),
http://www.example.com/articles/2014/12/
month_archive(request, year='2014', month='12')
Including other URLconfs
• Why is it useful?
• Note that the regular expressions in this example don’t have a $ (end-of-string match character) but do include a trailing slash.
• Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point.
from django.conf.urls import include, url
urlpatterns = [ url(r'^community/', include('django_website.aggregator.urls')), url(r'^contact/', include('django_website.contact.urls')), ]
Let's go back to views!
• When a page is requested, Django creates an HttpRequest object that contains metadata about the request.
from django.http import HttpResponse import datetime
def current_datetime(request): now = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % now return HttpResponse(html)
HttpRequest Class
• HttpRequest.scheme
• HttpRequest.path
• HttpRequest.method
• HttpRequest.GET (django.http.QueryDict object)
• HttpRequest.POST (django.http.QueryDict object)
• HttpRequest.COOKIES
• HttpRequest.META
• and a bunch of other things!
HttpResponse Class
• In contrast to HttpRequest objects, which are created automatically by Django, HttpResponse objects are your responsibility.
• Typical usage is to pass the contents of the page, as a string, to the HttpResponse constructor:
from django.http import HttpResponse
response = HttpResponse("Here's the text of the Web page.") response = HttpResponse("Not found, man.", status=404) response = HttpResponse("Text only, please.", content_type="text/html")
response['User-Custom-Header'] = 'Custom Value'
12
3
4
HttpResponse Subclasses
• HttpResponseRedirect
• HttpResponsePermanentRedirect
• HttpResponseBadRequest
• HttpResponseNotFound
• HttpResponseForbidden
• HttpResponseServerError
• JsonResponse
Let's see 'views' in action!
Showtime!
Any questions?
Thank you.
�23