[Zope] Re: Triggering the persistence mechanism
Chris McDonough
chrism at plope.com
Thu Dec 15 17:43:05 EST 2005
> session variables. What I want to be able to do is have the coders
> call
>
> getSessionVariable(name)
>
> to get the current value of the session variable and
>
> setSessionVariable(name, value)
>
> to save the value. The type of the variable should be transparent
> to the
> programmer--that is, it could be a number, a string, a dictionary,
> or a
> list.
The two functions you describe are all that you need.
>
> My question restated: Is there a way to write a generic
> setSessionVariable()routine that handles the mutated values properly
> for arbitrary types.
>
The simplest implementations are sufficient:
def getSessionVariable(name):
return context.request.SESSION[name]
def setSessionVariable(name, value):
context.request.SESSION[name] = value
Where this behaves in an unexpected manner is if someone stores a
mutable value in the session, e.g.:
setSessionVariable('a', {})
and *later in the same request* does something like this *without
ever again calling setSessionVariable*:
a = getSessionVariable('a')
a['foo'] = 'bar'
The programmer has mutated the dictionary, which is a basic type, and
thus doesn't know anything about persistence. Since it's mutated,
and its value isn't stored back into the session explicitly, it will
eventually disappear when the session data object is "ghosted".
The best (and only) way to prevent this is to instruct your
developers to always explicitly re-persist session variables after
they mutate them:
a = getSessionVariable('a')
a['foo'] = 'bar'
setSessionVariable('a', a)
There is no sane mechanism to prevent them from needing to do this
for mutable basic types.
> and mutated from the old value, whatever it may have been. Or is it
> necessary to specifically include an assignment for each mutated
> component of the dictionary or list?
It is not necessary to do this for each value in the dictionary or
list. Just for the dictionary or list itself.
>
> What happens when the value to be stored is a dictionary of
> dictionaries
> of lists and has been mutated?
The mutations are lost unless you call setSessionVariable on the top-
level dictionary.
>
> Is there an advantage to using the persistent Dictionary and List
> classes
> in the session rather than ordinary ones?
They avoid the requirement that you think about this, as they are not
basic types and thus know about persistence and can manage this for you.
>
> Thanks again for your insight.
- C
More information about the Zope
mailing list