[mod_python] MySQLSession available!! errata

Jim Gallacher jpg at jgassociates.ca
Mon Nov 27 17:26:17 EST 2006


Martijn Moeling wrote:
> 
> def mysql_cleanup(req): 
> should be 
> def MySQL_cleanup(req):
> 
> 
> can Multiple cleanups be registered? Modpython doc is not clear on that,
> and how about the order of processing,
> My handler registers a cleanup for closing the Db.
> This cleanup is "added".
> 
> -----Oorspronkelijk bericht-----
> Van: mod_python-bounces at modpython.org
> [mailto:mod_python-bounces at modpython.org] Namens Martijn Moeling
> Verzonden: Monday, November 27, 2006 16:09
> Aan: mod_python at modpython.org
> Onderwerp: [mod_python] MySQLSession available!!
> 
> Well after investigating "sessions.py" a bit more I have come up with a
> working MySQLSession object added to "sessions.py"
> 
> See code (only the changed parts) below....
> 
> The nasty thing is that it will be overwritten by any mod_python
> updates, or if it is interesting enough (hopefully) it gets into the
> next major mod_python release.
> 
> By checking for the req.cursor, there is no need for importing MySQLdb
> into session.py
> 
> See code (only the changed parts) below....
> 
> 8<---------------------------------------------------------------------
> ########################################################################
> ###
> ## MySQLSession
> ## M. Moeling, martijn at xs4us.nu
> ##
> ## In order to use MySQLSession:
> ## in your handler.py:        
> ## import MySQLdb
> ##
> ##  Somewhere before the session stuff use:
> ##
> ##  req.db =
> MySQLdb.connect(host=Chost,user=Cuser,passwd=Cpasswd,db=Cdb)
> ##  req.cursor = req.db.cursor()
> ## 
> ##  When req.cursor is existing, Session.py will default to MySQLSession
> ##  Can be overruled with pythonoptions in apache config
> ##
> ## To create table in MySQL use the following:
> ## CREATE TABLE `Session` (
> ##  `sid` varchar(50) NOT NULL,
> ##  `store` text NOT NULL,
> ##  PRIMARY KEY  (`sid`)
> ## ) TYPE=MyISAM;
>         
> def mysql_cleanup(req):
>     req.cursor.execute("Select * from Session")
>     AllSessions = req.cursor.fetchall()
>     for records in AllSessions:
>         session = cPicle.loads(record[1])
                     ^^^^^^
                     bug :(

>         if (time.time() - session["_accessed"]) > session["_timeout"]:
>             req.cursor.execute("DELETE FROM Session where
> sid='"+session[0]+"'")        


You might want to have separate fields for accessed and timeout in your 
table. That way you can do the cleanup with a single DELETE query. 
Unpickling *all* of the sessions just to read _accessed and _timeout can 
be are real performance killer if you have a lot of rows or the site is 
under heavy load. This one of the bottlenecks in DbmSession, but it is 
easily avoided with a sql database.

Jim


More information about the Mod_python mailing list