Source code for superdjango.sessions.library

# Exports

__all__ = (
    "Session",
)

# Classes


[docs]class Session(object): """A simplistic helper for working with session variables in a sane way."""
[docs] def __init__(self, request, prefix=None): """Initialize session interface. :param request: The current request. :type request: django.http.request.HttpRequest :param prefix: The variable name prefix, if any. :type prefix: str """ self.prefix = prefix self.request = request
[docs] def get(self, name, default=None): """Get a session variable, automatically prefixing the name. :param name: The variable name. :type name: str :param default: The value to use if no value is already set. """ name = self._get_name(name) # noinspection PyUnresolvedReferences return self.request.session.get(name, default)
[docs] def has(self, name): """Indicates whether the current session has the given variable. :rtype: bool """ name = self._get_name(name) # noinspection PyUnresolvedReferences return name in self.request.session
[docs] def set(self, name, value): """Set a session variable, automatically prefixing the name. :param name: The variable name. :type name: str :param value: The value to set. """ name = self._get_name(name) # noinspection PyUnresolvedReferences self.request.session[name] = value # https://stackoverflow.com/q/2166856/241720 # noinspection PyUnresolvedReferences self.request.session.modified = True
[docs] def unset(self, name): """Remove the named value from the session. :param name: The un-prefixed variable name. :type name: str """ name = self._get_name(name) # noinspection PyUnresolvedReferences if name in self.request.session: # noinspection PyUnresolvedReferences del(self.request.session[name])
def _get_name(self, name): """Get the variable name stored in the session, including the prefix if one has been provided. :param name: The un-prefixed variable name. :type name: str :rtype: str """ if self.prefix is not None: return "%s_%s" % (self.prefix, name) return name