It seems like the best approach, for my app at least, is to define a
decorator to handle the serializing and unserializing of objects
stored in session, e.g.
@sessionobjects
def mycontroller():
...
This seems to be working, but I'm wondering if it has any known
gotchas relative to the under-the-hood workings of web2py. For
example, will the session always remain unserialized until after the
view is rendered? Or within the context of a redirect?
If this implementation seems sound, I'll post it in a comment to the
sessions page of the online doc.
Here's the code for the decorator.
## -----------------------------------------------------
def sessionobjects(f):
"""
Web2py sessions can't store app-defined objects unless they are
pre-serialized.
This decorator ensures that a list of session member objects are
unserialized before use and re-serialized afterward.
It also serves as a default initializer for the members, setting
them to None if they don't exist.
"""
def new_f():
objnames = ["problem",] ## edit list to fit your app
for n in objnames:
## In normal python, you would use hasattr() to see
## if the member exists, but session is of class Storage
## which returns None if the member doesn't exist.
if None != getattr(session,n):
setattr(session,n,cPickle.loads(getattr(session,n)))
try:
return f()
finally:
for n in objnames:
setattr(session,n,cPickle.dumps(getattr(session,n)))
return new_f
## -----------------------------------------------------