[mod_python] Cookie vs. Session

Shawn Harrison harrison at tbc.net
Wed Feb 9 16:32:15 EST 2005


Jef Dodson wrote [02/09/05 2:56 PM]:
> Great, thanks.  So, I was able  to get cookies working but I would like to experiment with using
> Session objects.  Does anyone have some simple example code showing how to do basic stuff with a
> Session object like: Get the sessionid from a request to identify a particular user and if no
> session is found, create a  session object and send it back to the browser.  The documentation
> seems a little sparse in this area and I'm a little confused about how exactly session objects
> work in general.  Thanks again!

Yes, the documentation isn't as helpful as it could be. Maybe we should 
submit some patches.

First, I set the session after login. I put in a list of the groups that 
the user is a member of, as well as the user name, so that I can do 
group-based access control without querying the DB all the time:

     # This code is after login and the user has been verified.
     # The details are specific to my environment -- in particular, the
     # 'db' object. But you can get the idea. --SAH

     from mod_python import Session
     session = Session.Session(req)

     # Set the username and groups that this user belongs to
     grouplist = []

     # The following line would depend on your DB access method.
     # I have my own Database() class which provides select()
     # You'll probably use "cursor.execute(...)" and "cursor.fetchall()".
     groups = db.select('groups_memberships_users',
                        'groupname',
                        "username = '%s'" % user.name)
     for i in range(len(groups)):
         grouplist.append(groups[i].groupname)
     session['groups'] = "|".join(grouplist)
     session['user'] = user.name

     # save the session for next time.
     session.save()

Then, I have a function that my authen_handler uses for restricted areas 
of the site:

     from mod_python import apache, Session
     def require_group(req, group):
         # Check to see if the user has access to this group's resources.
         # returns an apache error status

         # see if the user has a session

         sess = Session.Session(req)
         sess.load()

         if sess.is_new():
             util.redirect(req, '/login?refpage=%s' % req.uri)
             return apache.OK
         else:
             # check out the user's login and group membership
             if sess.has_key('groups'): groups = sess['groups']
             else: groups=""
             groups = groups.split("|")
             if group in groups:
                 return apache.OK
             else:
                 return apache.HTTP_FORBIDDEN

-- 
________________
harrison at tbc.net


More information about the Mod_python mailing list