CE419 Session 13: Django Web Framework: Views Web Programming
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. 1 from django.http import HttpResponse import datetime 3 def current_datetime (request): now = datetime.datetime.now() 2 html = "<html><body>It is now %s.</body></html>" % now return HttpResponse(html) 4
URLconfs • Fire up the built-in web server! ~/myblog $ python manage.py runserver • Where is my view?!
URLconfs (cont'd) • Remember HTTP requests? GET /now/ HTTP/1.1 Host: mail.ce.sharif.edu Referer: http://mail.ce.sharif.edu/ Content-Length: 125 • 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.
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 3 2 urlpatterns = [ url( r '^now/$', 'posts.views.current_datetime'), 1 url(r'^login/$', 'users.views.login'), url(r'^admin/', include(admin.site.urls)), ]
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. https://www.facebook.com/groups/ 390233697744819 / http://www.imdb.com/title/tt 0816692 / https://twitter.com/ Arsenal /status/ 107858262212358144 https://itunes.apple.com/ us /genre/ ios-business /id6000 http://www.last.fm/user/ johndoe /now • We can use Regular Expressions to capture these. ^groups/ (\d+) /$ ^title/tt (\d+) /$ ^ (?P<username>\w+) /status/ (?P<tweet_id>\d+) $
Showtime! Let's see ' regular expressions' in action. � 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) 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') • Captured arguments are always strings.
Including other URLconfs • Why is it useful? from django.conf.urls import include, url urlpatterns = [ url(r'^community/', include('django_website.aggregator.urls')), url(r'^contact/', include('django_website.contact.urls')), ] • 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.
Let's go back to views! 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) • When a page is requested, Django creates an HttpRequest object that contains metadata about the request.
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.") 1 response = HttpResponse("Not found, man.", status=404) response = HttpResponse("Text only, please.", 2 content_type="text/html") 3 response['User-Custom-Header'] = 'Custom Value' 4
HttpResponse Subclasses • HttpResponseRedirect • HttpResponsePermanentRedirect • HttpResponseBadRequest • HttpResponseNotFound • HttpResponseForbidden • HttpResponseServerError • JsonResponse
Showtime! Let's see ' views ' in action!
Thank you. Any questions? � 23
Recommend
More recommend