You are viewing a plain text version of this content. The canonical link for it is here.
Posted to mod_python-commits@quetz.apache.org by Apache Wiki <wi...@apache.org> on 2006/12/19 23:47:15 UTC

[Mod_python Wiki] Update of "Cookie use with Classes" by MartinStoufer

Dear Wiki user,

You have subscribed to a wiki page or wiki category on "Mod_python Wiki" for change notification.

The following page has been changed by MartinStoufer:
http://wiki.apache.org/mod_python/Cookie_use_with_Classes

The comment on the change is:
Initial checking. Definetly needs more meat and input.

New page:
This is an extension of the [http://modpython.org/live/current/doc-html/pyapi-cookie-example.html 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.

{{{#!python
# This example uses an instance of the ExampleSession class for every request.

from mod_python import apache, Session, Cookie, util
from time import time
import types

_tags = (1,2,3,4)

class Instance:
   def __init__(self, target, *args, **kwargs):
       self.__target = target
       self.__args = args
       self.__kwargs = kwargs
       return

   def __call__(self, req):
       assert(type(self.__target) in [types.ClassType, types.TypeType])
       if not hasattr(req, 'session'):
          req.session = Session.Session(req)
       cookies = Cookie.get_cookies(req, Cookie.MarshalCookie,
                                    secret='secret007')
       target = self.__target(*self.__args, **self.__kwargs)
       return util.apply_fs_data(target, req.form, req=req, cookies=cookies)

class ExampleSession:
   def __call__(self, req, cookies):
       self._do_session(req)
       self._do_cookies(req, cookies)
       return self._output

   def __init__(self, *args, **kwargs):
       # Do something with the args here.
       self._output = """"""
       return


   def _do_session(self, req):
       try:
           delta = int(time()- req.session['last'])
       except KeyError:
           delta = 0
       total = int(time()- req.session.created())
       try:
           req.session['hits'] += 1
       except:
           req.session['hits'] = 1

       req.session['last'] = req.session.last_accessed()
       req.session.save()

       self._output += """Session ID: %s
This session has been active for %d seconds
This session was last accessed %d seconds ago
This session has been accessed %d times """ % \
           (req.session.id(), total, delta, req.session['hits'])
       return

   def _do_cookies(self, req, cookies):
       # Handle Cookie now
       if cookies and cookies.has_key('spam'):
           _spamcookie = cookies['spam']

           self._output += ("\nGreat, a spam cookie was found: %s\n" \
                                      % str(_spamcookie))
           if type(_spamcookie) is Cookie.MarshalCookie:
               self._output += ("Here is what it looks like decoded: %s=%s\n" % \
                               (_spamcookie.name, _spamcookie.value))
           else:
               self._output += ("""WARNING: The cookie found is not a
                               MarshalCookie, it may have been tapered with!""")
       else:
           # MarshaCookie allows value to be any marshallable object
           _new_cookie_value = {'egg_count': 42, 'color': 'white'}
           Cookie.add_cookie(req,
                   Cookie.MarshalCookie('spam', _new_cookie_value, 'secret007'))
           self._output += ("\nSpam cookie not found, but we just set one!\n")
       return

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