"""This is a MySQL backend for aquarium.session.DatabaseSessionContainer."""
__docformat__ = "restructuredtext"
# Created: Fri Jan 14 15:15:47 PST 2005
# Author: Jeffrey Wescott, Shannon -jj Behrens
# Email: jjinux@users.sourceforge.net
#
# Copyright (c) Jeffrey Wescott, Shannon -jj Behrens. All rights reserved.
import array
import time
from aquarium.util.AquariumClass import AquariumClass
from aquarium.session.SessionContainer import SessionContainer
import aquarium.conf.AquariumProperties as properties
class Session(AquariumClass):
TABLE_NAME = "Session"
__doc__ = \
"""This is a MySQL backend for aquarium.session.DatabaseSessionContainer_.
To use this module, you'll need to add this to your schema::
CREATE TABLE %(TABLE_NAME)s
(
sid CHAR(%(SID_LENGTH)s) NOT NULL,
last_modified TIMESTAMP NOT NULL,
pickle LONGBLOB,
PRIMARY KEY(sid)
);
To store pickles that are really large, you'll also need to update your
``my.cnf``:
[mysqld]
...
set-variable = max_allowed_packet=16M
The following class level constants are defined:
TABLE_NAME
This is the name of the table to store sessions in.
.. _aquarium.session.DatabaseSessionContainer:
aquarium.session.DatabaseSessionContainer-module.html
""" % {
"TABLE_NAME": TABLE_NAME,
"SID_LENGTH": SessionContainer.SID_LENGTH
}
def cleanup(self):
"""Delete all of the expired sessions."""
ctx = self._ctx
limit = time.time() - properties.MAXIMUM_SESSION_LIFETIME
ctx.dba.cursor().execute("""\
DELETE FROM %(TABLE_NAME)s
WHERE last_modified < from_unixtime(%(limit)s)
""" % {
"TABLE_NAME": self.TABLE_NAME,
"limit": limit
})
def exists(self, sid):
"""Does a session with the given sid exist?
This implies that it is not expired.
"""
ctx = self._ctx
cursor = ctx.dba.cursor()
esc = ctx.db.escape_string
limit = time.time() - properties.MAXIMUM_SESSION_LIFETIME
cursor.execute("""\
SELECT COUNT(*) AS sid_exists FROM %(TABLE_NAME)s
WHERE sid='%(sid)s'
AND last_modified >= from_unixtime(%(limit)s)
""" % {
"TABLE_NAME": self.TABLE_NAME,
"sid": esc(sid),
"limit": limit
})
return ctx.dba.fetchonedict(cursor, force=True)["sid_exists"]
def save(self, session, pickle):
"""Persist a session."""
ctx = self._ctx
query = """\
REPLACE INTO %s
(sid, last_modified, pickle)
VALUES (%%(sid)s, from_unixtime(%%(last_modified)s), %%(pickle)s)
""" % self.TABLE_NAME
args = {
"sid": session["sid"],
"last_modified": session["lastModified"],
"pickle": pickle
}
ctx.dba.cursor().execute(query, args)
def load(self, sid):
"""Load a session.
Return it in its pickled form.
"""
ctx = self._ctx
cursor = ctx.dba.cursor()
esc = ctx.db.escape_string
cursor.execute("""\
SELECT pickle FROM %(TABLE_NAME)s
WHERE sid='%(sid)s'
""" % {
"TABLE_NAME": self.TABLE_NAME,
"sid": esc(sid)
})
pickle = ctx.dba.fetchonedict(cursor, force=True)["pickle"]
if isinstance(pickle, array.array): # Workaround a MySQLdb bug.
pickle = pickle.tostring()
return pickle
|