Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
A Scenic Drive through the Django Request-Respo...
Search
PyCon 2014
April 12, 2014
Programming
7
1.6k
A Scenic Drive through the Django Request-Response Cycle by Dan Langer
PyCon 2014
April 12, 2014
Tweet
Share
More Decks by PyCon 2014
See All by PyCon 2014
Postgres Performance for Humans by Craig Kerstiens
pycon2014
29
3.6k
Technical Onboarding, Training, and Mentoring by Kate Heddleston and Nicole Zuckerman
pycon2014
1
2.3k
"My big gay adventure. Making, releasing and selling an indie game made in python." by Luke Miller
pycon2014
2
1.5k
Farewell and Welcome Home, Python in Two Genders by Naomi_Ceder
pycon2014
1
710
Deliver Your Software in an Envelope by Augie Fackler and Nathaniel Manista
pycon2014
1
520
Hitchhikers Guide to Free and Open Source Participation by Elena Williams
pycon2014
6
1.2k
Localization Revisted (aka. Translations Evolved) by Ruchi Varshney
pycon2014
0
690
Smart Dumpster by Bradley E. Angell
pycon2014
0
500
Software Engineering for Hackers: Bridging the Two Solitudes by Tavish Armstrong
pycon2014
0
710
Other Decks in Programming
See All in Programming
命名をリントする
chiroruxx
1
420
From Translations to Multi Dimension Entities
alexanderschranz
2
140
採用事例の少ないSvelteを選んだ理由と それを正解にするためにやっていること
oekazuma
2
1k
PHPで学ぶプログラミングの教訓 / Lessons in Programming Learned through PHP
nrslib
3
330
モバイルアプリにおける自動テストの導入戦略
ostk0069
0
110
Amazon S3 NYJavaSIG 2024-12-12
sullis
0
100
これが俺の”自分戦略” プロセスを楽しんでいこう! - Developers CAREER Boost 2024
niftycorp
PRO
0
190
useSyncExternalStoreを使いまくる
ssssota
6
1.2k
Асинхронность неизбежна: как мы проектировали сервис уведомлений
lamodatech
0
880
17年周年のWebアプリケーションにTanStack Queryを導入する / Implementing TanStack Query in a 17th Anniversary Web Application
saitolume
0
250
GitHubで育つ コラボレーション文化 : ニフティでのインナーソース挑戦事例 - 2024-12-16 GitHub Universe 2024 Recap in ZOZO
niftycorp
PRO
0
100
rails stats で紐解く ANDPAD のイマを支える技術たち
andpad
1
300
Featured
See All Featured
4 Signs Your Business is Dying
shpigford
182
21k
Save Time (by Creating Custom Rails Generators)
garrettdimon
PRO
29
900
Git: the NoSQL Database
bkeepers
PRO
427
64k
RailsConf & Balkan Ruby 2019: The Past, Present, and Future of Rails at GitHub
eileencodes
132
33k
Rebuilding a faster, lazier Slack
samanthasiow
79
8.7k
Gamification - CAS2011
davidbonilla
80
5.1k
Become a Pro
speakerdeck
PRO
26
5k
Adopting Sorbet at Scale
ufuk
73
9.1k
Writing Fast Ruby
sferik
628
61k
Into the Great Unknown - MozCon
thekraken
33
1.5k
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
251
21k
Art, The Web, and Tiny UX
lynnandtonic
298
20k
Transcript
THE DJANGO REQUEST-RESPONSE CYCLE A Scenic Drive Though Daniel Langer
[email protected]
@dlanger
DANIEL LANGER Je m’appelle Handmade in Toronto
THE DJANGO REQUEST-RESPONSE CYCLE A Scenic Drive Though
LOTS OF THESE Django has http://www.safetysign.com/images/catlog/product/large/J6014.png
CLIENT
THE REQUEST
THE REQUEST $ curl -v http://www.daniellanger.com/hello/mtl/
THE REQUEST $ curl -v http://www.daniellanger.com/hello/mtl/ > GET /hello/mtl/ HTTP/1.1
> Host: www.daniellanger.com > Accept: */*
http://www.google.com/about/datacenters/gallery/#/all/5 THE INTERNET http://www.google.com/about/datacenters/gallery/#/all/5
THE WEB SERVER http://bit.ly/1jPAhEC
INTERFACE? mod_python FastCGI CGI
WEB SERVER GATEWAY INTERFACE PEP 333 December 2007 Phillip Eby
WEB SERVER GATEWAY INTERFACE def simple_app(environ, start_response): response_headers = [('Content-type',
'text/plain')] start_response(‘200 OK’, response_headers) return ['Hello world!\n']
DJANGO SPEAKS WSGI class WSGIHandler(base.BaseHandler): def __call__(self, environ, start_response): [...]
response = self.get_response(request) [...] start_response(status, response_headers) return response
DJANGO.CORE.HANDLERS.BASEHANDLER 1. Request middleware 2. Resolve request.path_info 3. View middleware
4. View 5. Response middleware * Exception middleware (maybe)
MIDDLEWARE? A small digression
MIDDLEWARE A small digression “[A] light, low-level ‘plugin’ system for
globally altering Django’s input or output.” - https://docs.djangoproject.com/en/dev/topics/http/middleware/
MIDDLEWARE A small digression MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', [...]
)
DJANGO.CORE.HANDLERS.BASEHANDLER 1. Request middleware 2. Resolve request.path_info 3. View middleware
4. View 5. Response middleware * Exception middleware (maybe)
REQUEST MIDDLEWARE class PyConRequestMiddleware(object): def process_request(self, request): return None #
or HttpResponse
BREAK TIME http://bit.ly/1mNlxWE
CLIENT WEB SERVER WSGI REQUEST Middleware
DJANGO.CORE.HANDLERS.BASEHANDLER 1. Request middleware 2. Resolve request.path_info 3. View middleware
4. View 5. Response middleware * Exception middleware (maybe)
DJANGO.CORE.URLRESOLVERS http://www.daniellanger.com/hello/mtl/
DJANGO.CORE.URLRESOLVERS http://www.daniellanger.com/hello/mtl/ urlpatterns = patterns('' url(r'^hello/mtl/$', HiMtlView, name=‘hi__mtl’), url(r'^hello/(?P<city>\w+)/$', HiCityView,
name=‘hi_city’), )
DJANGO.CORE.URLRESOLVERS http://www.daniellanger.com/hello/mtl/ urlpatterns = patterns('' url(r'^hello/(?P<city>\w+)/$', HiCityView, name=‘hi_city’), url(r'^hello/mtl/$', HiMtlView,
name=‘hi__mtl’), ]
DJANGO.CORE.URLRESOLVERS urlpatterns = patterns('' url(r'^hello/(?P<city>\w+)/$', HiCityView, name=‘hi_city’), ) {% url
‘hi_city’ city=ottawa %} reverse(‘hi_city’, kwargs={‘city’: ‘ottawa’}) # Both return http://www.daniellanger.com/hello/ottawa/
DJANGO.CORE.URLRESOLVERS urlpatterns = patterns('' url(r'^cdn_hi/(?P<city>\w+)/$', HiCityView, name=‘hi_city’), ) {% url
‘hi_city’ city=ottawa %} reverse(‘hi_city’, kwargs={‘city’: ‘ottawa’}) # Both return http://www.daniellanger.com/cdn_hi/ottawa/
DJANGO.CORE.URLRESOLVERS http://www.daniellanger.com/hello/mtl/ urlpatterns = patterns('' url(r'^hello/mtl/$', HiMtlView, name=‘hi__mtl’), url(r'^hello/(?P<city>\w+)/$', HiCityView,
name=‘hi_city’), )
DJANGO.CORE.HANDLERS.BASEHANDLER 1. Request middleware 2. Resolve request.path_info 3. View middleware
4. View 5. Response middleware * Exception middleware (maybe)
DJANGO.CORE.HANDLERS.BASEHANDLER 1. Request middleware 2. Resolve request.path_info 3. View middleware
4. View 5. Response middleware * Exception middleware (maybe)
VIEWS def HiMtlView(request): html = “Bonjour <b>Mtl</b>!” return HttpResponse(html)
RESPONSES? HttpResponse HttpResponseRedirect JsonResponse StreamingHttpResponse
VIEWS def HiMtlView(request): html = “Bonjour <b>Mtl</b>!” return HttpResponse(html)
CLASS-BASED VIEWS from django.views.generic import View class HiMtlView(View): def get(self,
request): html = “Bonjour <b>Mtl</b>!” return HttpResponse(html)
TEMPLATES IN VIEWS from django.shortcuts import render def HiMtlView(request): context
= {‘city’: ‘Montreal’} return render(request, ‘hello.html’, context) # hello.html Bonjour <b>{{ city }}</b>!
TEMPLATES IN VIEWS def HiMtlView(request): context = {‘city’: ‘Montreal’} return
render(request, ‘hello.html’, context) # hello.html Bonjour <b>{{ city }}</b> (from {{ request_city }}!)
TEMPLATES IN VIEWS def HiMtlView(request): context = { ‘city’: ‘Montreal’,
‘request_city’: GeoIP.get_city(request)} return render(request, ‘hello.html’, context) # hello.html Bonjour <b>{{ city }}</b> (from {{ request_city }}!)
CONTEXT PROCESSORS def HiMtlView(request): context = { ‘city’: ‘Montreal’, ‘request_city’:
GeoIP.get_city(request)} return render(request, ‘hello.html’, context) # hello.html Bonjour <b>{{ city }}</b> (from {{ request_city }}!)
CONTEXT PROCESSORS def request_city(request) return { ‘request_city’: GeoIP.get_city(request), }
CONTEXT PROCESSORS def HiMtlView(request): context = {‘city’: ‘Montreal’} return render(request,
‘hello.html’, context) # hello.html Bonjour <b>{{ city }}</b> (from {{ request_city }}!)
The Doe Corporation presents PAUSE PAUSE- CAFE http://www.roadfood.com/photos/20865.jpg
CLIENT WEB SERVER WSGI URL RESOLUTION VIEW REQUEST Middleware VIEW
Middleware
DJANGO.CORE.HANDLERS.BASEHANDLER 1. Request middleware 2. Resolve request.path_info 3. View middleware
4. View 5. Response middleware * Exception middleware (maybe)
RESPONSE MIDDLEWARE class PyConResponseMiddleware(object): def process_response(self, request, response): return None
# or HttpResponse
MIDDLEWARE class PyConMiddleware(object): def process_request(self, request): return None # or
HttpResponse def process_response(self, request, response): return response # or new HttpResponse
MIDDLEWARE MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'PyConMiddleware', [...] )
DJANGO.CORE.HANDLERS.BASEHANDLER 1. Request middleware 2. Resolve request.path_info 3. View middleware
4. View 5. Response middleware * Exception middleware (maybe)
EXCEPTION MIDDLEWARE class PyConMiddleware(object): def process_exception(self, request, exception): return None
# or HttpResponse
WEB SERVER GATEWAY INTERFACE class WSGIHandler(base.BaseHandler): def __call__(self, environ, start_response):
[...] response = self.get_response(request) [...] start_response(status, response_headers) return response
THE RESPONSE $ curl -v http://www.daniellanger.com/hello/mtl/ > GET /hello/mtl/ HTTP/1.1
> Host: www.daniellanger.com > Accept: */* < HTTP/1.1 200 OK < Server: nginx < Content-Type: text/html;charset=UTF-8 < Content-Length: 33 Bonjour Montreal! (from Toronto)
CLIENT WEB SERVER WSGI URL RESOLUTION VIEW WSGI WEB SERVER
CLIENT REQUEST Middleware RESPONSE Middleware VIEW Middleware EXCEPTION Middleware
@dlanger