session information in cgi scripts

James Gregory james at anchor.net.au
Thu Mar 27 08:42:24 EST 2003


On Thu, 2003-03-27 at 11:10, James Gregory wrote:

> Is something like this possible? Would the garbage collector do things
> in the appropriate order? How do I define a destructor? And most
> importantly: has someone already done this?

So, I decided to try it out. The code is below. Now I have a more
tangible problem; I put this:

if not globals().has_key('data') :
    global data
    data = Data()

at the end of the module with the intent that I would then be able to
refer to it as session.data[key] from elsewhere in the code.
Unfortunately when I do this, the page fails every second reload. I
believe the internal server error is clobbering the cookie so on every
odd reload it figures it needs to make a new dictionary and things all
work (but the values aren't persistent of course)

The problem is that if I remove that little block of code and just
import the module and create the session manually, it all works
perfectly. In fact, if I get another class to create a session in it's
constructor (and this newly created object is also global - it's a
database handle), it will work perfectly.

At a guess I'd say I'm hitting a problem with garbage collection, but
I'm really not sure. Sorry about the clag, but it's pretty short. Here's
the code:

        import pickle, Cookie
        from os import environ
        from posix import tmpnam
        from pprint import pprint
        
        class Data (dict) :
            def __init__ (self) :
                cookies = Cookie.SmartCookie()
                d = {}
                try :
                    cookies.load(environ['HTTP_COOKIE'])
                except :
                    pass
                # mostly the cookie will be set.
                try :
                    self.filename = cookies['SESSION'].value
                    file = open(self.filename)
                    d = pickle.load(file)
                except KeyError :
                    self.filename = tmpnam()
                    # touch the file.
                    file = open(self.filename, 'w')
                    file.close()
                    cookies['SESSION'] = self.filename
                    print cookies
        
                dict.__init__(self, d)
        
            def __del__ (self) :
                file = open(self.filename, 'w')
                pickle.dump(self, file)
        
        if not globals().has_key('data') :
            global data
            data = Data()
        
And my simple test:
        
        import session
        from pprint import pprint
        
        try :
            session.data['number'] += 1
        except KeyError :
            session.data['number'] = 1
        
        print "Content-type:text/html\n"
        pprint (session.data)
        
Any help greatly appreciated.

James.







More information about the Python-list mailing list