Cookies and Sessions in Django
Cookies and Sessions in Django
This slide deck consists of slides used in 2 lecture videos in Week 1. Below is a list of
shortcut hyperlinks for you to jump into specific sections.
Cookies and
Sessions
https://samples.dj4e.com/session/
Browser Linux
WGSIConfig settings.py
Django
urls.py
Parse
D
O
Response Cookies and Sessions
M
Templates
views.py
forms.py
N
G
I
N models.py Database
X
Javascript
Multi-User / Multi-Browser
• When a server is interacting with many different browsers at the
same time, the server needs to know *which* browser a
particular request came from.
http://en.wikipedia.org/wiki/HTTP_cookie
HTTP cookie
http://en.wikipedia.org/wiki/HTTP_cookie
Cookies In the Browser
• Cookies are marked as to the web addresses they come from. The
browser only sends back cookies that were originally set by the
same web server.
• Cookies have an expiration date. Some last for years, others are
short-term and go away as soon as the browser is closed
Cookies
https://samples.dj4e.com/session/
https://github.com/csev/dj4e-samples/blob/master/session/home/views.py
Cookies
https://github.com/csev/dj4e-samples/blob/master/session/home/views.py
def cookie(request):
print(request.COOKIES)
resp = HttpResponse('C is for cookie and that is good enough for me...')
resp.set_cookie('zap', 42) # No expired date = until browser close
resp.set_cookie('sakaicar', 42, max_age=1000) # seconds until expire
return resp
In the log:
[29/Sep 23:17:55] "GET /session/cookie HTTP/1.1" 200 26
{'sessionid': 'xy414ikma0p80jw19mrg146inewhzp3s', 'zap':
'42', 'sakaicar': '42'}
Cookies
https://samples.dj4e.com/session/
https://github.com/csev/dj4e-samples/blob/master/session/home/views.py
Cookies
def cookie(request):
print(request.COOKIES)
resp = HttpResponse('C is for cookie and that is good enough for me...')
resp.set_cookie('zap', 42) # No expired date = until browser close
resp.set_cookie('sakaicar', 42, max_age=1000) # seconds until expire
return resp
Cookies
Cookies
Time
Cookies
Browser Browser Browser Browser
zap=42 zap=42 zap=42
zap=42
Apache
Django
Code
Django Sessions
https://samples.dj4e.com/session/sessfun
https://github.com/csev/dj4e-samples/tree/master/session
Browser Linux
WGSIConfig settings.py
Django
Click Session 3e
Middleware
6f
4
D
O
Parse
Response Sessions urls.py
2
M
Templates
views.py
forms.py
N
G
I
N models.py Database
X
Javascript
In the Server - Sessions
• In most server applications, as soon as we start a session for a new
(unmarked) browser we create a session.
• This number is used to pick from the many sessions that the server has
active at any one time.
• Server software stores data in the session that it wants to have from
one request to another from the same browser.
https://github.com/csev/dj4e-samples/blob/master/dj4e-samples/settings.py
Default – Store Sessions in the
Database
$ python3 manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
...
Applying auth.0009_alter_user_last_name_max_length... OK
Applying sessions.0001_initial... OK
Sessions Space
Django C12
3
Django Sessions
• The incoming request object has a request.session attribute
that we can treat like a dictionary that persists from one
request to the next request
• As long we have the session middleware enabled in
settings.py and the database table, and the browser allows
cookies, we just store and read request.session in our views
and pretend it is "magic"
Sessions
def sessfun(request) :
num_visits = request.session.get('num_visits', 0) + 1
request.session['num_visits'] = num_visits
if num_visits > 4 : del(request.session['num_visits'])
return HttpResponse('view count='+str(num_visits))
https://github.com/csev/dj4e-samples/blob/master/session/views.py
Sessions
https://github.com/csev/dj4e-samples/blob/master/session/views.py
Sessions
Sessions
Sessions
$ sqlite3 db.sqlite3
SQLite version 3.24.0 2018-06-04 14:10:15
Enter ".help" for usage hints.
sqlite> .tables
auth_group auth_user_user_permissions
auth_group_permissions django_admin_log
auth_permission django_content_type
auth_user django_migrations
auth_user_groups django_session
sqlite> .mode column
sqlite> select * from django_session;
vosaoain2dzw0o8bzlgsmovdbkp574us
YThiZWRjMjQ1NzZhMzYzMTBhZjYxNWI2ZDgyODI1Y2ExODI2MTJjNzp7Im51bV92aXNpdHMiOjF9
2019-02-21 15:18:34.995362
vii016kh2vzqpm0uw3or4qrqxddmwisx
OWNkOGQxYjg4NzlkN2ZhOTc2NmU1ODY0NWMzZmQ4YjdhMzM4OTJhNjp7Im51bV92aXNpdHMiOjJ9
2019-02-21 15:32:52.555061
sqlite> .quit
What is in the Django Session Table?
$ python3
>>> import base64
>>> x = base64.b64decode(
... 'OWNkOGQxYjg4NzlkN2ZhOTc2NmU1ODY0NWMzZmQ4YjdhMzM4OTJhNjp7Im51bV92aXNpdHMiOjJ9')
>>> print(x)
b'9cd8d1b8879d7fa9766e58645c3fd8b7a33892a6:{"num_visits":2}'
>>> import json
>>> data = json.loads(x[41:])
>>> print(data)
{'num_visits': 2}
>>>
Summary
• HTTP Cookies
• Sessions
• Using Sessions in Django
Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance Continue new Contributors and Translators here
(www.dr-chuck.com) as part of www.wa4e.com and
made available under a Creative Commons Attribution
4.0 License. Please maintain this slide in all copies of
the document to comply with the attribution
requirements of the license. If you make a change,
feel free to add your name and organization to the list
of contributors on this page as you republish the
materials.