159.352 Topic 4 — Exercises
Sessions and cookies
Here the important takeaway is the key difference between sessions and cookies—session variables are stored server-side and cookie variables are stored client-side.
Sessions
Starting with a simple server program, define a dictionary structure called sessiond. This will be used to store your server-side “session data”. Then . . .
1. Modify your server so that it will count the number of “hits” the server received—i.e. the number of times any client has accessed the site.
2. Modify further so that the session state data are saved when the server is stopped, and then restored when the server is restarted.
3. Modify further to track user authentication (username and password). If not authen- ticated, then direct to a login page. Note: this authentication mechanism is different from HTTP authentication.
Cookies
Low level support for HTTP cookies is available in the Python http.cookies module. Here we also make use of the datetime module. Again, starting with a basic server, make a simple cookie data object
c = http .cookies .SimpleCookie()
This will be used to store different cookies. Make a cookie with a name and value only. The value can be any string you like
c [ ' grover ' ] = ' zaq1234 '
Make another cookie with an expiry date. First use the datetime module to get a date-time object to represent 30 days from NOW
expires = datetime .datetime .utcnow() + datetime .timedelta(days=30)
Now make the cookie and set the expiry date using an appropriate string format for the date
c [ ' cookiemonster ' ] = ' dsh93373 '
c [ ' cookiemonster ' ][ ' expires ' ] = expires .strftime( "%a , %d %b %Y %H:%M:%S GMT " )
Now send send each cookie in an HTTP header. We need suitable string representations of these. This is done using “morsels”:
for m in c .values():
print(m .OutputString())
self.send_header( ' Set-Cookie ' , m .OutputString())
Get all of this working in a server program and try connecting using a browser. Have a look at the headers that get exchanged.
You can also write your own client using the request module and examine the cookies there. First get a session object and make a GET request to the server
session = requests .Session()
session .get( ' http://localhost:8080 ' )
We can then iterate through the cookies and examine their attributes, e.g.:
for c in session .cookies :
print(c .name , c .expires)
As well as your own server, use your client to examine the cookies sent from other sites, e.g.:
https://www. google . com
https://www . nzherald . co . nz
https://www . wikipedia . com
Consider how you would modify your client to store cookies client-side, and send them back to the server.