0% found this document useful (0 votes)
10 views32 pages

Cookies and Sessions in Django

This document is a slide deck covering Week 1 topics on Cookies and Sessions in Django. It explains how cookies are used to maintain state in stateless HTTP transactions and how Django manages sessions through middleware. The content includes code examples and details on setting up session management in a Django application.

Uploaded by

zinzirakallu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views32 pages

Cookies and Sessions in Django

This document is a slide deck covering Week 1 topics on Cookies and Sessions in Django. It explains how cookies are used to maintain state in stateless HTTP transactions and how Django manages sessions through middleware. The content includes code examples and details on setting up session management in a Django application.

Uploaded by

zinzirakallu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Table of Contents

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.

• (page 2) Week 1: Cookies and Sessions

• (page 15) Week 1:Django Sessions


Charles Severance
www.dj4e.com

Cookies and
Sessions

https://samples.dj4e.com/session/
Browser Linux
WGSIConfig settings.py

Django

Click Session Session


Middleware Storage

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.

• Request / Response initially was stateless - all browsers looked


identical . This was really bad and did not last very long at all.
Web Cookies to the Rescue
Technically, cookies are arbitrary pieces of data chosen
by the Web server and sent to the browser. The
browser returns them unchanged to the server,
introducing a state (memory of previous events) into
otherwise stateless HTTP transactions. Without
cookies, each retrieval of a Web page or component of
a Web page is an isolated event, mostly unrelated to all
other views of the pages of the same site.

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

set_cookie request.COOKI request.COOKI request.COOKI


() ES ES ES

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.

• We set a session cookie to be stored in the browser, which indicates


the session id in use – gives this browser a unique “mark”.

• The creation and destruction of sessions is handled by a Django


middleware that we use in our applications.
Session Identifier
• A large, random number that we place in a browser cookie the first
time we encounter a browser

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

• Shopping cart or login information is stored in the session in the


server.
Middleware
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

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

Browser Browser Browser


S=A123 S=B345 S=C678

Django Session Middleware

A12 B34 C67


Web Server 3 5 8
Time
Sessions
Browser Browser Browser Browser
S=C123 S=C123 S=C123 S=C123

request request request ... request


POST GET POST POST
session session session session

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.

Initial Development: Charles Severance, University of


Michigan School of Information

Insert new Contributors and Translators here including


names and dates
Additional Source Information
• Cookie Image: By brainloc on sxc.hu (Bob Smith) (stock.xchng) [CC BY 2.5
(http://creativecommons.org/licenses/by/2.5)], via Wikimedia Commons
• Portions of the text of these slides is adapted from the text www.djangoproject.org web site. Those slides which
use text from that site have a reference to the original text on that site. Django is licensed under the three-clause
BSD license.

You might also like