session is an Storage, Storages always return an attribute, defaults to
None.

You do not have to always access session objects by keys, you can do it by
attribute and it will always return an object, even if the object does not
exists.

examples

my_var = getattr(session, request.controller)

Even when you have nothing in session, it will return an object with value
"None"

>>> from gluon.storage import Storage
>>> session = Storage()
>>> my_var = getattr(session, "blablabla")
>>> my_var
>>> print my_var
None
>>> session.anything = "blah"
>>> print getattr(session, "anything")
blah
>>> print session.anything
blah
>>> print session["anything"]
blah
>>> print session.banana
None
>>> print session["ohohohoho"]
None
>>> print getattr(session, "jsdnfgkjsdnfjkds")
None
>>>

On Thu, Feb 9, 2012 at 7:38 PM, Cliff <[email protected]> wrote:

> In an index function I do something like
> session[request.controller].something = 'foo'
>
> This raises a key error exception on the first visit to the controller
> after restarting the browser.  Session can't find the controller name,
> so I can't add an attribute to it.  So I need to initialize the
> session, but not clobber it if already set.
>
> After several hours this puzzling behavior emerged:
>
> print session # request.controller not there, as expected.
> # nothing but auth
> print hasattr(session, str(request.controller)) # Prints True.
> ## Previous result not expected!! Why??
> print request.controller in session # Prints False, as expected
> session[request.controller] = {}
> print hasattr(session, str(request.controller)) # Prints True
> ## As expected this time.
> print request.controller in session # Prints True, as expected
> print session[request.controller] # Prints {}, as expected
>
> Can someone tell me why hasattr(session, str(request.controller))
> returned true when request.controller was not an attribute of session?
>
> Thanks,
> Cliff Kachinske
>
>


-- 

Bruno Rocha
[http://rochacbruno.com.br]

Reply via email to