[mod_python] python rewrite of mod_usertrack (actual module this time)

geoff at ijane.com geoff at ijane.com
Fri Jun 16 11:19:33 EST 2000


Sorry.
I didn't realize that attachment didn't work.
Here is the module (usertrack.py):

"""This module is a shameless rewrite of mod_usertrack in python.  It should
operate in most respects like mod_usertrack.  The exception would be that it
always sets a 4 digit year for an expire date.

Logging
This will be handled by mod_log_config, the custom log module.  The cookie
will be available by using the token, "%{session_cookie}n".
For example:

LogFormat "%t \"%r\" %>s \"%{session_cookie}n\"" session
CustomLog /usr/local/apache/logs/session_log session

PythonOptions
There are three options that can be configured: CookieExpires, CookieName
and CookieTracking.   These basically work the same as mod_usertrack's
directives of the same name.

CookieExpires
This option sets an expiration time for the cookie generated by this module.
This time can be either a number of seconds or a string describing the
amount of time.  If this option does not exist the cookie will expire when
the browser's session does.  The time string must be quoted and is in the
format of a space separeated list of "number label" pairs.  Valid labels
are: years, months, weeks, days, hours, minutes, seconds.

CookieName
If this option exists the default name of the cookie will be whatever the
label specifies.

CookieTracking
This option is required if you will to use this module.  It's value must be
"on" for this module to operate.


httpd.conf example:

<Directory />
    PythonPath "['/usr/lib/python1.5', '/usr/lib/python1.5/site-packages']"

    PythonDebug
    PythonOption CookieName k3WL_c00KI3_nAM3
    PythonOption CookieTracking on
    PythonOption CookieExpires "10 years 4 months 2 weeks 3 days 2 hours 36
seconds"
    PythonFixupHandler usertrack
</Directory>

"""
__version__ = "$Id: usertrack.py,v 1.1 2000/06/02 09:00:31 geoff Exp $"
from mod_python import apache
import re, string, time, os

isDigit = re.compile("^\d+$")
isSpace = re.compile("\s+")

FACTOR = {
    'years': 60 * 60 * 24 * 365,
    'months': 60 * 60 * 24 * 30,
    'weeks': 60 * 60 * 24 * 7,
    'days': 60 * 60 * 24,
    'hours': 60 * 60,
    'minutes': 60,
    'seconds': 1,
    }            

COOKIE_NAME = "Apache_Python"

def fixuphandler(r):
    global COOKIE_NAME
    opt = r.get_options()
    if opt['CookieTracking'] != 'on':
        return apache.DECLINED
    else:
        if opt.has_key('CookieName'): COOKIE_NAME = opt['CookieName']
        try:
            m = re.search("(?:^|\s+)%s=(?P<cookieValue>[^;]+)" %
COOKIE_NAME, \
                          r.headers_in['Cookie'])
            r.notes['session_cookie'] = m.group('cookieValue')
            return apache.DECLINED
        except:
            expires = 0
            if opt.has_key('CookieExpires'):
                expires = r.request_time + \
                                 parseExpire(opt['CookieExpires'])
            make_cookie(r, COOKIE_NAME, expires)
    return apache.OK
        
def make_cookie(r, name, expires):
    """Set a unique cookie for user tracking."""
    cookieValue = "%s.%d%ld%ld" % (r.hostname, os.getpid(), r.request_time,
\
                                   time.clock())
    if expires == 0:
        r.headers_out['Set-Cookie'] = "%s=%s; path=/" % (name, \
                                                         cookieValue)
    else:
        r.headers_out['Set-Cookie'] = "%s=%s; path=/; expires=%s GMT" % \
            (name, cookieValue, time.strftime("%A, %d-%b-%Y %H:%M:%S", \
            time.gmtime(expires)))  
    r.notes['session_cookie'] = cookieValue
    return

def parseExpire(expire):
    """Return number of seconds from a formated string."""
    if isDigit.search(expire): return expire
    seconds = 0
    t = isSpace.split(expire)
    tLen = len(t)
    i = 0
    while i < tLen:
        if isDigit.search(t[i]):
            seconds = seconds + (FACTOR.get(string.lower(t[i + 1]), 0) * \
                                 string.atoi(t[i]))
        i = i + 2
    return seconds



More information about the Mod_python mailing list