I was working with webpy sessions and ran into an error with file
concurrency. This isn't a problem if you use the DB store version of
sessions, but for the file store it was causing tracebacks (trying to
unpickle empty strings).  I found this issue with multiple connections
reading and writing to the same session file -- I was serving static
content with authorization in front of it (only show graphs to people
who are owners of such assets).

To fix it, I implemented a subclass of DiskStore, called
UnixDiskStore. This only works with systems that implement fcntl
obviously -- any windows developers want to implement a
WindowsDiskStore or add that functionality to this one? I don't know
enough about windows file io to get that working with any confidence,
and it'd be nice to get this functionality back into the source tree.

As an added bonus, this also clears up race conditions if there are
more than one webpy process running simultaneously.

Hope this is useful to other people too.

Cheers,
Justin


### UnixDiskStore implementation ###

import web, os, fcntl

class UnixDiskStore(web.session.DiskStore):
    """ Implement file locking, only works with posix systems """

    def __getitem__(self, key):
        path = self._get_path(key)
        if os.path.exists(path):
            try:
                f = open(path)
                fcntl.flock(f.fileno(), fcntl.LOCK_SH)
                pickled = f.read()
            finally:
                fcntl.flock(f.fileno(), fcntl.LOCK_UN)
                f.close()
            return self.decode(pickled)
        else:
            raise KeyError, key

    def __setitem__(self, key, value):
        path = self._get_path(key)
        pickled = self.encode(value)
        try:
            f = open(path, 'w')
            try:
                fcntl.flock(f.fileno(), fcntl.LOCK_EX)
                f.write(pickled)
            finally:
                fcntl.flock(f.fileno(), fcntl.LOCK_UN)
                f.close()
        except IOError:
            pass

-- 
You received this message because you are subscribed to the Google Groups 
"web.py" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/webpy?hl=en.

Reply via email to