[mod_python] Sessions (Aaaarggghhhh!!)

Jim Gallacher jpg at jgassociates.ca
Mon Jan 16 22:20:36 EST 2006


Luis M. Gonzalez wrote:
> Hi Folks!
> 
> I'm needing some help with this problem...
> I just started playing with mod_python yesterday, and after pulling my hair with installation problems and configurations,
> I managed to get it working and I also could write some basic little apps.
> 
> Right now, I'm almost finished with a simple shopping cart, wich is an instance of class "cart" and contains, obviously, items with their prices and quantities.
> It performs the usual actions, such add item, update quantity, etc.
> The problem is that when I perform any of these actions, the cart is created again, and the previous information gets lost.
> It seems that there's a problem with my session handling, but I can't figure out what's wrong...
> 
> This is how I create the session for my shopping cart:
> 
> s = Session.Session(req)
> 
> s = Session.Session(req)

I assume this is a copy and paste error, but if it's not... do *not* 
create 2 session objects in the same request. Session locking (which is 
on by default) will result in a deadlock.

> if not hasattr(s,'x'):
>     s['x']= cart()

You can also use s.is_new() to determine if this is a new session which 
may require some sort of initialization code for your cart.

Sessions are saved as pickles, and you are likely to run into problems 
trying to save an instance of your class in the session. It's best to 
stick to simple types like strings, integers and so on (including lists 
and dicts).

>     s.save() 
> 
>  and this is the code that handles the operations:
> 
> if form['action']=='upqty':
>     try:
>         if int(form['qty'])==0:
>             del s['x'].items[form['item']]
>             s.save()
>         else:
>             s['x'].upqty(form['item'],int(form['qty']))
>             s.save()
>         s['x'].pp()
>         
>     except:
>         print 'Bad entry. Try again...with numbers'
> elif form['action']=='ad':
>     try:
>         if form['item']=='':
>      print 'no item to add'
>         else:
>      s['x'].ad(form['item'],float(form['price']),int(form['qty']))
>             s.save()
>          s['x'].pp()
>             
>     except:
>  print 'Bad entry. Try again...with numbers'
> s.save()   


You will likely have better luck if you just save a list of your cart 
data in the session.

items = [{'item':form['item'], 'qty':form['qty']}, {.. more items ..}, ]
s['cart_items'] = items
s.save()

As an aside doing all those saves is going to kill your performance as 
each save requires pickling the data and writing it to disk (unless you 
are using MemorySession and apache mpm-threaded on windows). Just do one 
save at the end of your code block.

Jim





More information about the Mod_python mailing list