[mod_python] mod_python session p roblem

Graham Dumpleton grahamd at dscpl.com.au
Sun Apr 2 18:54:29 EDT 2006

> > yjfuk wrote:
> > 
> >>code below:
> >>from mod_python import Session
> >>def index(req)
> >>  sess=Session.Session(req)
> >>  if sess.is_new():
> >>    sess['num']=0
> >>    sess.save()
> >>  else:
> >>    sess['num']+=1
> >>    sess.save()
> >>    req.write(str(sess['num']))
> >> 
> >> 
> >>when I reflush the browser some times ,the session is usually lost .
> >>I run it in windows XP(sp2),python 2.4.2, mod_python 3.2.8

Is this really the complete code you were using to experiment with
or have you thrown out a lot of stuff?

I ask as since you were using req.write(), no content type would be
set for case where existing session used and an empty response
would result from where it is a new session. Thus, the responses
wouldn't necessarily be as useful as they could be. This is assuming
the indenting of your code was simply stuffed up in one of the

Oh, there is also a ':' missing off function prototype, but again that
may also have dissappeared in posts.

The important thing is, if this isn't all your code, then it is possible
that the problem lies in stuff you didn't post.

Jim Gallacher wrote ..
> The code you show here looks OK, so I'm not sure what the problem may be.
> So is a new session created for every request, where you always see "0"
> returned in the response? Or do you sometimes see some number greater
> than "0", and then sometimes "0"? This is unclear in your original
> message as well.
> Is there anything in the apache error log indicating a problem?

I would suggest you experiment with something like the following code:

  from mod_python import Session
  import time

  def index(req):

    timestamp = time.time()

    req.log_error("index %s" % `timestamp`)

    req.content_type = 'text/plain'


    if sess.is_new():

    req.write("index %s\n" % `timestamp`)

    req.write("num %d\n" % str(sess['num']))

The point of the logging is to prove that the function did in fact get
called. The point of returning the timestamp in the response is to
prove that you are in fact getting a different fresh page on each access

If it isn't a problem in some other code of yours, one possibility if
you are accessing the server through a proxy is that you have an
overly agressive proxy cache. This can be a problem with GET requests
in some situations and in worst cases it may be necessary to specify
explicitly that responses should not be cached.

When you work out the problem or if you already have, please followup
saying it is fixed and describe what the problem is. :-)


More information about the Mod_python mailing list