[mod_python] Cookie vs. Session

Byron Ellacott bje at apnic.net
Wed Feb 9 00:41:57 EST 2005


On 09/02/2005, at 11:21 AM, Jef Dodson wrote:

> This might be a naive question, but how does one know whether to use a 
> Cookie or a Session for
> session/state management?  What are the major differences?  My 
> interest is in simply allowing
> someone to login to a site and then be able to identify that user when 
> they make subsequent
> requests in order to send them customized content.  So, this is pretty 
> standard stuff, but is it
> better to use cookies or session objects for this.  Thanks.

A 'session' usually refers to server held state per-user; it requires 
some form of session identifier to be shuttled back and forth between 
client and server, often via a cookie.  They are primarily useful when 
you are building some sort of working set of data for a user, such as a 
sequentially filled in form.  They are often overused. :)

A cookie is a piece of browser-held information given to a server when 
a URL with an appropriate domain is fetched.

For your purposes, simply using a cookie to identify your user may be 
sufficient.  Note that a cookie is stored browser side, so you must be 
able to verify a cookie's authenticity to a level appropriate for your 
purposes.  It sounds like you're not necessarily showing any sensitive 
information, or in any other way relying on user identification for 
security, so you could easily get away with simply storing the user 
name in a cookie:

--- snip ---
from mod_python import Cookie

def get_user_credentials(req):
     cookies = Cookie.get_cookie(req)
     if cookies.has_key('username'):
         return cookies['username']
     # redirect to login page ...

def set_user_credentials(req, username):
     cookie = Cookie.Cookie('username', username)
     Cookie.add_cookie(req, cookie)
--- snip ---

So, the first function will try to get the user's name from a cookie.  
If one is not found, you should redirect to the login page, or return 
None, or whatever is appropriate behaviour for your application.  The 
second function should be called from your login page, to create and 
store a cookie with the user's  name.

Just bear in mind, it would be trivial to spoof yourself to appear to 
be another user with such a simple scheme.  If this is in any way bad, 
you would probably want to consider at least using a SignedCookie 
instead of a regular Cookie object.  The documentation for the Cookie 
module can help you further.

-- 
bje



More information about the Mod_python mailing list