CherryPy Project Download

Using CherryPy with Dejavu

Dejavu is an Object-Relational Mapper library, supporting MySQL, PostgreSQL, SQLite, Microsoft Access, Microsoft SQL Server, shelve, and custom stores. To use it with CherryPy, we create a new sandbox for each request, using a tool which then cleans it up for us automatically:

import types
import cherrypy
from cherrypy._cperror import format_exc

def flush_sandbox():
    if hasattr(cherrypy.request, "sandbox"):
        try:
            try:
                cherrypy.request.sandbox.flush_all()
            except:
                cherrypy.log(format_exc(), "DEJAVU")
        finally:
            del cherrypy.request.sandbox

def try_flush_sandbox():
    if cherrypy.response.stream:
        # If the body is being streamed, we have to save the data
        #   *after* the response has been written out
        cherrypy.request.hooks.attach('on_end_request', flush_sandbox)
    else:
        # If the body is not being streamed, we save the data now
        if isinstance(cherrypy.response.body, types.GeneratorType):
            cherrypy.response.collapse_body()
        flush_sandbox()

class SandboxTool(cherrypy.Tool):
    def _setup(self):
        cherrypy.request.sandbox = endue.arena.new_sandbox()
        cherrypy.Tool._setup(self)
tools.sandbox = SandboxTool('on_end_resource', try_flush_sandbox)

Turn it on and then reference cherrypy.request.sandbox in your page handlers. In your startup script (the one that calls cherrypy.server.start), write:

myapp.arena.load(r"C:\myapp\myappsm.conf")

The filename should be that of a Dejavu configuration file. How's *that* for simple integration? :)

Older versions

2.2

class DejavuSandboxFilter(object):
    """Creates and auto-flushes a Dejavu Sandbox for each request."""
    
    def onStartResource(self):
        """Called after the request body has been read/parsed"""
        cherrypy.request.sandbox = endue.arena.new_sandbox()
    
    def onEndRequest(self):
        """Called after writing the response (header & body included)"""
        if hasattr(cherrypy.request, "sandbox"):
            try:
                try:
                    cherrypy.request.sandbox.flush_all()
                except:
                    cherrypy.log(_cputil.formatExc(), "DEJAVU")
            finally:
                del cherrypy.request.sandbox

Hosted by WebFaction

Log in as guest/cherrypy to create/edit wiki pages