CE419 Session 13: Django Web Framework: Views Web Programming - - PowerPoint PPT Presentation

ce419
SMART_READER_LITE
LIVE PREVIEW

CE419 Session 13: Django Web Framework: Views Web Programming - - PowerPoint PPT Presentation

CE419 Session 13: Django Web Framework: Views Web Programming Review ModelTemplateView architecture Views and URLconfs Django has the concept of views to encapsulate the logic responsible for processing a users request and for


slide-1
SLIDE 1

CE419 Web Programming

Session 13: Django Web Framework: Views

slide-2
SLIDE 2

Review

  • Model—Template—View architecture
slide-3
SLIDE 3

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

slide-4
SLIDE 4

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

slide-5
SLIDE 5

URLconfs

  • Fire up the built-in web server!
  • Where is my view?!

~/myblog $ python manage.py runserver

slide-6
SLIDE 6

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

slide-7
SLIDE 7

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.”

slide-8
SLIDE 8

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

1 2 3

slide-9
SLIDE 9

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/

slide-10
SLIDE 10

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+)$

slide-11
SLIDE 11

Let's see 'regular expressions' in action.

Showtime!

11

slide-12
SLIDE 12

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

slide-13
SLIDE 13

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.

slide-14
SLIDE 14

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

slide-15
SLIDE 15

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

slide-16
SLIDE 16

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)

slide-17
SLIDE 17

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!
slide-18
SLIDE 18

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'

1 2 3 4

slide-19
SLIDE 19

HttpResponse Subclasses

  • HttpResponseRedirect
  • HttpResponsePermanentRedirect
  • HttpResponseBadRequest
  • HttpResponseNotFound
  • HttpResponseForbidden
  • HttpResponseServerError
  • JsonResponse
slide-20
SLIDE 20

Let's see 'views' in action!

Showtime!

slide-21
SLIDE 21

Any questions?

Thank you.

23