If you're OK with only storing the variables for the duration of the
session (i.e. not persisting across server restarts), then an easy way
is to store the data in some sort of dictionary and save the key into
the dictionary as a cookie.
Yeah, that's correct.
Another way is to store the whole thing in the cookie by pickling it.
I don't know how big your data is but I assume there are size limits
on cookies, so this wouldn't really work for very complicated things.
You could even do it compressed:
def usersave(obj): return web.setcookie('state',
zlib.compress(pickle.dumps(obj)))
def userget(obj): return
pickle.loads(zlib.decompress(web.cookies().get('state', '')))
Otherwise you'll have to use some persistant storage mechanism like a
file on disk or a database or something.
Please, _please_, do not do this. This is like SQL injection, except
instead of giving the attacker access to your database, you're giving
him access to the python interpreter instead.
I quote from the pickle documentation: The pickle module is not
intended to be secure against erroneous or maliciously constructed
data. Never unpickle data received from an untrusted or
unauthenticated source.
If you must do this, I'd recommend using JSON. It'll compress well,
and it'll be easier to do a basic sanity check on it. Also, it'll be
less likely to allow an attacker to include bad stuff.
If you're running webpy as cgi, I presume you're using flup?
http://webpy.org/track/wiki/SessionsWithFlup
If you have a lot of classes you could probably have a base class
that does self.session = web.ctx.environ[...].session in __init__
and use self.session in your GET/POST handlers.
Untested. Caveat Emptor.
--
David Terrell
d...@meat.net
((meatspace)) http://meat.net/
Oops, yeah. Don't use the pickle module. Someone should add JSON to
the standard library.
If you absolutely positively HAVE to store real state objects on the
clientside, they'd better be encrypted with an HMAC, because you never
know what's going to be an attack vector to subvert your library.
For a brief(!) example of how to do this, try this on:
http://meat.net/src/securecookie.py
requires pycrypto: http://www.amk.ca/python/code/crypto
Well, easy_install simplejson isn't _that_ hard.
simplejson is very well written, but there's a catch. If you're doing
UTF-8, make sure you ensure_ascii=False whenever calling dumps(). I
don't know what it is with it that it will give you funky \uSOMETHING
sequences for every non-ascii byte, and although that may display
right in HTML/JS, you should want to keep raw UTF-8 for better
interoperability (specially with other JSON parsers).
--Jonas Galvez