Package lemon.session
PHP-style session management.
Version
=======
File Version 0.1 for LEMON 0.2
Dependencies
============
* db module for database storage.
Overview
========
The session module is designed to provide the ability to manage sessions to allow data to persist between HTTP
requests. It is not designed to have reliable expiring or any fancy authorisation features. This is the job of
modules built using the session module. An example of such a module is the auth module.
Introduction
============
Every time a script calls the session.start() function a new session is begun unless one already exists. If a new
session is created it will last for at least the time set by the expire parameter but may last longer. If you
choose to use cookies you can set the expire time of the cookie independantly from that of the session. This means
the cookie could expire well before the session is destroyed.
Each application which uses the seession module has its own name. This means that many applications can use the
same session without risk of over-writing each others variables. This is useful in the case that a user visits a
site which uses the session module for multiple applications.
Session variables can be set or retrieved using the get() and set() methods of the session object returned by the
session.start() function or by treating the session object as a dictionary.
The class is designed to work in a similar way to PHP sessions.
get(key) set(key, value) delete(key):
key - a string maximum of 32 characters which is not in the list of blocked variables
value - any datastructure that can be pickled eg a string, integer, dictionary etc.
A quick example application:
import lemon.session, lemon, lemon.db
session = lemon.session.start(storage='db', app='test', database=lemon.db.connect(type='mysql', database='test') )
if session.created():
print "Content-type: text/html
"
print "<html><h1>This is your first visit</h1><p>Setting variable1 to 'Python Rules!'.</p><p>Refresh this page...</p></html>"
session.set('variable1','Python Rules!')
else:
if lemon.cgi.has_key('destroy'):
session.destroy()
print "Content-type: text/html
<html><h1>Session Deleted</h1></html>"
else:
print "Content-type: text/html
<html><h1>Welcome back</h1><p>variable1: "
print session['variable1'],
print '</p><p><a href="session.py?destroy=True">Destroy session</a>.</p></html>'
Notice how you can use either the functional interface session.set('variable1','Python Rules!') or the dictionary
interface print session['variable1'] to set and retrive session variables.
See the session example in doc/examples/code/session.py
Setting up your environment for sessions
========================================
The session module has a sub-module named 'manager'. This is use to setup the environment in which sessions are
stored so that you can separate your session related code from the code which sets up the environment.
Quick example to setup the sessions database using Gadfly:
import lemon.db
import lemon.session.manager
databaseConnection = lemon.db.connect(type='gadfly', startup=True, dir='C: estdir', database='test')
sessionManger = lemon.session.manager.start(storage='db', database=databaseConnection)
errors = sessionManger.createTables(autoCommit=True)
if errors:
for error in errors:
print error
databaseConnection.commit()
print "All Done."
To use a MySQL database you would change the databaseConnection line to:
databaseConnection = lemon.db.connect(type='mysql', database='test')
where test is the name of the database you wish to use. You would not need to specify autoCommit=True becuase
the MySQL conncetion does not require you to commit your changes after every table creation but the Gadfly
conncetion does.
To remove the environment use sessionManger.dropTables(autoCommit=True) rather than
sessionManger.createTables(autoCommit=True)
For a full example of how to use the session.manager module to setup or remove the session environment see the
files:
* scripts/dbCreateTables.py
* scripts/dbDropTables.py
Drivers
=======
The session module is implemented in a way which makes it easy to write drivers for more ways of storing session
information whilst the person actually using the session module still uses the same interface regardless of
the storge driver they are using.
Currently only the database driver is written. Ideally MySQL or a similar database
should be used as the session store. If you do not have access to such a database, the sql module comes with a
pure Python database called Gadfly which can be used to store the sessions.
Why Not Write A File-Based Driver?
==================================
We could have written a file based driver similar to that used by PHP but there are two reasons why it is not
necesary:
1. If you use Gadfly as the database you end up with file based storage without the need to set anything up
because Gadfly stores the data in files anyway.
2. It is more secure to store your session information in an SQL database such as MySQL becasue other users will
not have read access to the information. This is an issue in PHP and the manual suggests employing additional
security mesures if data needs to be secure.
Writing a Module Based On Session
=================================
The session classes allows some keys to be 'reserved' so the user of the module cannot use those keys. This
allows a module writer to use the session store to store important variables which the user of the module should
not have access to.
reserve(name) # Add a reserved application name.
release(name) # Remove the block for the application.
An example of an application which uses these features is the auth module which sets information such as when the
application was started, when it was last accessed etc.
Session Destruction
===================
Every time a session is accessed or created there is a certain probability (specified by the cleanup parameter)
that the session module will look through all sessions to see which ones have expired, removing session information
as necessary. This means sessions don't necessarily get destroyed when they expire. Setting the cleanup parameter too high means unnecessary work is done checking expired session more than is
needed. Too low and data may persist for a long time meaning that it takes a long time to cleanup the sessions once
the cleanup process if finally begun.
Once a session has expired the data cannot be accessed by the session module. If a user tries to access an expired
session, the session is destroyed immediately.
You can manually destroy the session using the destroy() function as demonstrated in the first example.
ToDo
====
Talk about a session store, reserving and releasing varibales
Write about
- Using the session module
- Developing a module based on the session module
- Adding a new driver to the session module
Submodules |
-
drivers : Drivers for the Session Module.
-
base : Base class for session storage drivers.
-
db : Implementation of a database storage driver for the session module.
-
manager : PHP-style authorisation functions.
-
drivers : Drivers for the Session Manager module.
-
base : PHP-style authorisation functions.
-
db : PHP-style authorisation functions.
|
Function Summary |
|
start (storage,
app,
expires,
sessionID,
cookie,
seed,
cleanup,
database,
table)
Parameters:
If the parameters are not set, the defaults are loaded from the Lemon.ini file. |
start(storage,
app,
expires=1440,
sessionID=None,
cookie={'comment': 'A web application built in Python using libs...,
seed='Built with Python',
cleanup=1,
database=None,
table='Session')
Parameters:
If the parameters are not set, the defaults are loaded from the Lemon.ini file.
Essential:
storage - Storage driver to use: 'db','text' etc...
app - Session name used in the Session table and as the Cookie name. Max length 255 characters.
Essential for 'db':
database - Lemon database connection to use.
Optional:
sessionID - The sessionID to use for the session (if set, cookies are not used).
expires - The length of the session.
seed - A character string to use as a seed when generating session Ids.
cleanup - 1 means the sessions are always cleaned up. 0 means they are
never cleaned up. 0.01 means 1 in 100 times the sessions will be cleaned.
cookie - A dictionary containing standard cookie parameters. Use defaults
if you don't understand the parameters:
path - The path for which the cookie is valid.
domain - The domain for which the cookie is valid.
secure - Whether to use secure cookies (set to True if needed).
comment - A comment describing what the cookie is for.
version - Is always 1.
max-age - Set by the expires parameter above.
# XXX Possible to implement idles as well??
-
|
__author__
-
- Type:
-
str
- Value:
'James Gardner [email: james at xecos.com]'
|
|
__credits__
-
- Type:
-
str
- Value:
'Guido van Rossum, for an excellent programming language.'
|
|
__date__
-
- Type:
-
str
- Value:
|
__version__
-
- Type:
-
str
- Value:
|
cookieOptions
-
- Type:
-
dict
- Value:
{'comment': 'A web application built in Python using libsession.',
'domain': '',
'lifetime': 0,
'max-age': 1000,
'path': '/',
'secure': 0,
'version': 1}
|
|