Reputation: 499
I've noticed that I can treat the session
object as an object (session.myVal = 'foo'
) as well as a dict (session['myVal'] = 'foo'
). You can't access a value set with the dict syntax with the object syntax, or visa versa. What is the correct way to use the session object?
Upvotes: 2
Views: 3046
Reputation: 127190
The only valid way to set values on the session is by treating the session as a dictionary (session[key] = value
). The dict items will be preserved between requests. See the docs for more information.
The session is a normal Python class instance, so it's perfectly valid to set attributes on it, but these won't effect the actual session data, they will just disappear when the request is over.
You can verify this for yourself: set an attribute on the session (session.xyz = '123'
), then try to print it out on a subsequent request (print(session.xyz)
), you'll get an AttributeError
.
Upvotes: 8
Reputation: 4268
In Python, a dict-like attribute getter and object-like attribute getter is both implemented by magic methods (which is started and ended with __
).
For example, you can define a dict-like object with magic methods __getitem__
and __setitem__
:
class D:
data = dict(attr1=1, attr2=2)
def __getitem__(self, name):
return self.data.get(name)
print D()['attr1']
Or, you can create an object-like attribute getter class with __getattr__
and __setattr__
:
class D:
data = dict(attr1=1, attr2=2)
def __getattr__(self, name):
return self.data.get(name)
print D().attr1
Both are OK. You can have a deeper look at the difference between __getattr__
and __getattribute__
in this link. More info about Python magic method could be found here.
In this case, a session
object is werkzurg.local.LocalProxy
object, which defines both __getattr__
and __getitem__
, that's why it can be used in two ways.
In my personal opinion, it's only about code style, which I prefer obj.attr
. That's because, I think IDE would be easier to get understand attribute getter, and give me a better tips support. It would be more important when you need to rename an attribute when refactoring.
Update: In the case of session
, it does have some self-defined attributes, so session['attr']
would be a safer choice.
Upvotes: -1