1# -*- coding: utf-8 -*-
2"""
3    webapp2_extras.appengine.sessions_memcache
4    ==========================================
5
6    Extended sessions stored in memcache.
7
8    :copyright: 2011 by tipfy.org.
9    :license: Apache Sotware License, see LICENSE for details.
10"""
11from google.appengine.api import memcache
12
13from webapp2_extras import sessions
14
15
16class MemcacheSessionFactory(sessions.CustomBackendSessionFactory):
17    """A session factory that stores data serialized in memcache.
18
19    To use memcache sessions, pass this class as the `factory` keyword to
20    :meth:`webapp2_extras.sessions.SessionStore.get_session`::
21
22        from webapp2_extras import sessions_memcache
23
24        # [...]
25
26        session = self.session_store.get_session(
27            name='mc_session',
28            factory=sessions_memcache.MemcacheSessionFactory)
29
30    See in :meth:`webapp2_extras.sessions.SessionStore` an example of how to
31    make sessions available in a :class:`webapp2.RequestHandler`.
32    """
33
34    def _get_by_sid(self, sid):
35        """Returns a session given a session id."""
36        if self._is_valid_sid(sid):
37            data = memcache.get(sid)
38            if data is not None:
39                self.sid = sid
40                return sessions.SessionDict(self, data=data)
41
42        self.sid = self._get_new_sid()
43        return sessions.SessionDict(self, new=True)
44
45    def save_session(self, response):
46        if self.session is None or not self.session.modified:
47            return
48
49        memcache.set(self.sid, dict(self.session))
50        self.session_store.save_secure_cookie(
51            response, self.name, {'_sid': self.sid}, **self.session_args)
52