[mod_python] Sessions again...

Graham Dumpleton grahamd at dscpl.com.au
Thu Jan 19 18:01:33 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.
> (Note that I also tried starting different sessions for each script, with
> different names, but the problem persists).
> 
> 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:

That is not a wacky work around, it is what must be done. For any
scripts which are located under the same PythonHandler directive, the
session object initialisation, ie., what is done when s.is_new() is
true, must be the same for all scripts. If not done like this, as you
are finding, when the other script is run it will be missing what it
needs as it hasn't has the opportunity to do its initialisation. The
other option as Jim pointed out is to effectively ignore s.is_new() and
simply add a default for the value if the attribute isn't present.

In general it is a good idea to separate out initialisation for a new
session object into a separate common routine which all scripts call, if
there are special attributes which need to be set up.

Graham

> 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...
> 
> Luis
> 
> 
> 
> > You'll need to clarify your problem a little, but I think you may be
> > assuming that you get a different session object for each script. That
> is 
> > not the case, at least by default. You get one session object per browser
> > so if you want to use it in independent scripts, each script will need
> to 
> > catch the KeyError exception or do some other test to see if you need
> to 
> > initialize your session data.
> >
> > You can also do some thing like this:
> >
> > r.counter = sess.get('counter', 0)
> > ...
> > ...
> > r.counter += 1
> > sess['counter'] = r.counter
> > sess.save()
> >
> > Jim
> > 
> 
> _______________________________________________
> Mod_python mailing list
> Mod_python at modpython.org
> http://mailman.modpython.org/mailman/listinfo/mod_python


More information about the Mod_python mailing list