Session 13: Django Web Framework: Views Web...

21
CE419 Web Programming Session 13: Django Web Framework: Views

Transcript of Session 13: Django Web Framework: Views Web...

Page 1: Session 13: Django Web Framework: Views Web Programmingce.sharif.edu/courses/94-95/2/ce419-1/resources/root/... · 2020. 9. 7. · ├── settings.py ... • Typical usage is to

CE419 Web Programming

Session 13: Django Web Framework: Views

Page 2: Session 13: Django Web Framework: Views Web Programmingce.sharif.edu/courses/94-95/2/ce419-1/resources/root/... · 2020. 9. 7. · ├── settings.py ... • Typical usage is to

Review

• Model—Template—View architecture

Page 3: Session 13: Django Web Framework: Views Web Programmingce.sharif.edu/courses/94-95/2/ce419-1/resources/root/... · 2020. 9. 7. · ├── settings.py ... • Typical usage is to

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

Page 4: Session 13: Django Web Framework: Views Web Programmingce.sharif.edu/courses/94-95/2/ce419-1/resources/root/... · 2020. 9. 7. · ├── settings.py ... • Typical usage is to

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

Page 5: Session 13: Django Web Framework: Views Web Programmingce.sharif.edu/courses/94-95/2/ce419-1/resources/root/... · 2020. 9. 7. · ├── settings.py ... • Typical usage is to

URLconfs

• Fire up the built-in web server!

• Where is my view?!

~/myblog $ python manage.py runserver

Page 6: Session 13: Django Web Framework: Views Web Programmingce.sharif.edu/courses/94-95/2/ce419-1/resources/root/... · 2020. 9. 7. · ├── settings.py ... • Typical usage is to

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

Page 7: Session 13: Django Web Framework: Views Web Programmingce.sharif.edu/courses/94-95/2/ce419-1/resources/root/... · 2020. 9. 7. · ├── settings.py ... • Typical usage is to

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

Page 8: Session 13: Django Web Framework: Views Web Programmingce.sharif.edu/courses/94-95/2/ce419-1/resources/root/... · 2020. 9. 7. · ├── settings.py ... • Typical usage is to

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

Page 9: Session 13: Django Web Framework: Views Web Programmingce.sharif.edu/courses/94-95/2/ce419-1/resources/root/... · 2020. 9. 7. · ├── settings.py ... • Typical usage is to

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/

Page 10: Session 13: Django Web Framework: Views Web Programmingce.sharif.edu/courses/94-95/2/ce419-1/resources/root/... · 2020. 9. 7. · ├── settings.py ... • Typical usage is to

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

Page 11: Session 13: Django Web Framework: Views Web Programmingce.sharif.edu/courses/94-95/2/ce419-1/resources/root/... · 2020. 9. 7. · ├── settings.py ... • Typical usage is to

Let's see 'regular expressions' in action.

Showtime!

�11

Page 12: Session 13: Django Web Framework: Views Web Programmingce.sharif.edu/courses/94-95/2/ce419-1/resources/root/... · 2020. 9. 7. · ├── settings.py ... • Typical usage is to

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

Page 13: Session 13: Django Web Framework: Views Web Programmingce.sharif.edu/courses/94-95/2/ce419-1/resources/root/... · 2020. 9. 7. · ├── settings.py ... • Typical usage is to

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.

Page 14: Session 13: Django Web Framework: Views Web Programmingce.sharif.edu/courses/94-95/2/ce419-1/resources/root/... · 2020. 9. 7. · ├── settings.py ... • Typical usage is to

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

Page 15: Session 13: Django Web Framework: Views Web Programmingce.sharif.edu/courses/94-95/2/ce419-1/resources/root/... · 2020. 9. 7. · ├── settings.py ... • Typical usage is to

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

Page 16: Session 13: Django Web Framework: Views Web Programmingce.sharif.edu/courses/94-95/2/ce419-1/resources/root/... · 2020. 9. 7. · ├── settings.py ... • Typical usage is to

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)

Page 17: Session 13: Django Web Framework: Views Web Programmingce.sharif.edu/courses/94-95/2/ce419-1/resources/root/... · 2020. 9. 7. · ├── settings.py ... • Typical usage is to

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!

Page 18: Session 13: Django Web Framework: Views Web Programmingce.sharif.edu/courses/94-95/2/ce419-1/resources/root/... · 2020. 9. 7. · ├── settings.py ... • Typical usage is to

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

Page 19: Session 13: Django Web Framework: Views Web Programmingce.sharif.edu/courses/94-95/2/ce419-1/resources/root/... · 2020. 9. 7. · ├── settings.py ... • Typical usage is to

HttpResponse Subclasses

• HttpResponseRedirect

• HttpResponsePermanentRedirect

• HttpResponseBadRequest

• HttpResponseNotFound

• HttpResponseForbidden

• HttpResponseServerError

• JsonResponse

Page 20: Session 13: Django Web Framework: Views Web Programmingce.sharif.edu/courses/94-95/2/ce419-1/resources/root/... · 2020. 9. 7. · ├── settings.py ... • Typical usage is to

Let's see 'views' in action!

Showtime!

Page 21: Session 13: Django Web Framework: Views Web Programmingce.sharif.edu/courses/94-95/2/ce419-1/resources/root/... · 2020. 9. 7. · ├── settings.py ... • Typical usage is to

Any questions?

Thank you.

�23