[mod_python] Sessions again...

Jim Gallacher jpg at jgassociates.ca
Thu Jan 19 19:17:59 EST 2006


Luis M. Gonzalez wrote:
> Ok, Jim, I'll clarify the problem:
> Both scripts initiate their sessions the same way and with the same name:
> 
> Script nr.1:
> 
>    s= Session.Session(req)
>    if s.is_new():
>       s['items'] = {}
> 
> Script nr.2:
> 
>    s= Session.Session(req)
>    if s.is_new():
>       s['counter'] = 0
> 
> I did it this way because I asume that for using both scripts in the 
> same site, I should have only one session started.

You are correct, but as you've discovered the order that the scripts are 
called by the client will effect which initialization routine will be 
executed. This is one of the things that can make using sessions tricky.

> (Note that I also tried starting different sessions for each script, 
> with different names, but the problem persists).

The name is not relevant. The thing that counts is the value of the 
pysid cookie which is set in the browser. It is this cookie that 
determines which session will be instantiated when Session.Session is 
called. A new session is created if there is no cookie, otherwise the 
corresponding session data is pulled from the persistent store.

> Actually, I already fixed this problem (with a wacky work-around 
> though...).
> In each script, I created the session variable corresponding to the 
> other script, as follows:
> 
> Script nr.1:
> 
>    s = Session.Session(req)
>    if s.is_new():
>        s['counter'] = 0
>        s['items']= {} # workaround to avoid trouble with cart script
> 
> Script nr.2:
> 
>    s = Session.Session(req)
>    if s.is_new():
>        s['items']= {}
>        s['counter'] = 0 # workaround to avoid trouble with recset script
> 
> Well, this fixed the problem in this case, but i don't think this 
> woraround fits into mod_python's best practices...

It may look ugly, but it's not totally wacky. The problem is that it 
will make maintainence more difficult as you are coupling 2 scripts that 
may not be related. If you want to make changes in script #2 12 months 
from now, will you remember why you have s['items'] = {} in there when 
it's not used anywhere else in that particular script? You might be 
better off using some combination of is_new and hasattr.

nr.1:
if not hasattr(s, 'counter') or s.is_new():
     do_nr1_session_init(s)

nr.2:
if not hasattr(s, 'items') or s.is_new():
     do_nr2_session_init(s)

If you really do want distinct session objects for each script you'll 
need to investigate some of the options Graham presented in another 
email in this thread.

Jim


More information about the Mod_python mailing list