Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Exports
3__all__ = (
4 "Session",
5)
7# Classes
10class Session(object):
11 """A simplistic helper for working with session variables in a sane way."""
13 def __init__(self, request, prefix=None):
14 """Initialize session interface.
16 :param request: The current request.
17 :type request: django.http.request.HttpRequest
19 :param prefix: The variable name prefix, if any.
20 :type prefix: str
22 """
23 self.prefix = prefix
24 self.request = request
26 def get(self, name, default=None):
27 """Get a session variable, automatically prefixing the name.
29 :param name: The variable name.
30 :type name: str
32 :param default: The value to use if no value is already set.
34 """
35 name = self._get_name(name)
37 # noinspection PyUnresolvedReferences
38 return self.request.session.get(name, default)
40 def has(self, name):
41 """Indicates whether the current session has the given variable.
43 :rtype: bool
45 """
46 name = self._get_name(name)
48 # noinspection PyUnresolvedReferences
49 return name in self.request.session
51 def set(self, name, value):
52 """Set a session variable, automatically prefixing the name.
54 :param name: The variable name.
55 :type name: str
57 :param value: The value to set.
59 """
60 name = self._get_name(name)
62 # noinspection PyUnresolvedReferences
63 self.request.session[name] = value
65 # https://stackoverflow.com/q/2166856/241720
66 # noinspection PyUnresolvedReferences
67 self.request.session.modified = True
69 def unset(self, name):
70 name = self._get_name(name)
72 # noinspection PyUnresolvedReferences
73 if name in self.request.session:
74 # noinspection PyUnresolvedReferences
75 del(self.request.session[name])
77 def _get_name(self, name):
78 """Get the variable name stored in the session, including the prefix if one has been provided.
80 :param name: The un-prefixed variable name.
81 :type name: str
83 :rtype: str
85 """
86 if self.prefix is not None:
87 return "%s_%s" % (self.prefix, name)
89 return name