This is an extension of the Cookies example in the mod_python manual. This example does not imply that the use of cookies in classes is in anyways better than using a direct function. I supply this example to show how you could incorporate cookie use in your existing class based implementation.

Again we include the Session object and use the Publisher model to return content to the browser.

The nominal URL for this example is:

  http://your.domain.com/ExampleSession/ExampleCookieSession.py/foo

   1 # This example uses an instance of the ExampleSession class for every request.
   2 # Save this file as ExampleCookieSession.py and store it in ${HTDOC_ROOT}/ExampleSession/
   3 
   4 from mod_python import apache, Session, Cookie, util
   5 from time import time
   6 import types
   7 
   8 _tags = (1,2,3,4)
   9 _secret = 'secret007'
  10 
  11 class Instance:
  12    def __init__(self, target, *args, **kwargs):
  13        self.__target = target
  14        self.__args = args
  15        self.__kwargs = kwargs
  16        return
  17 
  18    def __call__(self, req):
  19        global _secret
  20        assert(type(self.__target) in [types.ClassType, types.TypeType])
  21        if not hasattr(req, 'session'):
  22           req.session = Session.Session(req)
  23        cookies = Cookie.get_cookies(req, Cookie.MarshalCookie,
  24                                     secret=_secret)
  25        target = self.__target(*self.__args, **self.__kwargs)
  26        return util.apply_fs_data(target, req.form, req=req, cookies=cookies)
  27 
  28 class ExampleSession:
  29    def __call__(self, req, cookies):
  30        self._do_session(req)
  31        self._do_cookies(req, cookies)
  32        return self._output
  33 
  34    def __init__(self, *args, **kwargs):
  35        # Do something with the args here.
  36        self._output = """"""
  37        return
  38 
  39 
  40    def _do_session(self, req):
  41        try:
  42            delta = int(time()- req.session['last'])
  43        except KeyError:
  44            delta = 0
  45        total = int(time()- req.session.created())
  46        try:
  47            req.session['hits'] += 1
  48        except:
  49            req.session['hits'] = 1
  50 
  51        req.session['last'] = req.session.last_accessed()
  52        req.session.save()
  53 
  54        self._output += """Session ID: %s
  55 This session has been active for %d seconds
  56 This session was last accessed %d seconds ago
  57 This session has been accessed %d times """ % \
           (req.session.id(), total, delta, req.session['hits'])
  58        return
  59 
  60    def _do_cookies(self, req, cookies):
  61        # Handle Cookie now
  62        global _secret
  63        if cookies and cookies.has_key('spam'):
  64            _spamcookie = cookies['spam']
  65 
  66            self._output += ("\nGreat, a spam cookie was found: %s\n" \
                                      % str(_spamcookie))
  67            if type(_spamcookie) is Cookie.MarshalCookie:
  68                self._output += ("Here is what it looks like decoded: %s=%s\n" % \
                               (_spamcookie.name, _spamcookie.value))
  69            else:
  70                self._output += ("""WARNING: The cookie found is not a
  71                                MarshalCookie, it may have been tapered with!""")
  72        else:
  73            # MarshaCookie allows value to be any marshallable object
  74            _new_cookie_value = {'egg_count': 42, 'color': 'white'}
  75            Cookie.add_cookie(req,
  76                    Cookie.MarshalCookie('spam', _new_cookie_value, _secret))
  77            self._output += ("\nSpam cookie not found, but we just set one!\n")
  78        return
  79 
  80 foo=Instance(ExampleSession, _tags)

If this example looks to be a bit too much to digest, please review the simpler Session_use_with_classes examples.

Starting in the Instance.__call__ method, we are now explicitly pulling out the cookies attribute from the req object. We do not care at this time if the cookie is set, this is done later in your class if needed.

With the addition of the 'cookies' argument, we define a new method to handle the extraction/setting of cookie information. From here, you can easily extend your code to customize cookie use.


CategoryExamples

Cookie_use_with_Classes (last edited 2009-09-20 22:14:38 by localhost)