Search code examples
cherrypyzodb

Standard way to disconnect from database in cherrypy?


I'm using zodb with cherrypy. I'm passing data into a jinja2 template. I would like to close my zodb connection before I return the template render.

I can't because the template needs the connection when it's rendering because the data is zodb data.

This errors out...

zconn.close() #zconn.close closes the conn,db, and storage
return template.render(args....)

How do I close down the zodb conn after I'm already finished returning? Is there some "before request" and "after request" function I can define to always have a db connection? The cherrypy documentation doesn't have much explicit stuff on database connections save for "do it explicitly at the beginning of the exposed function - and close it before you return".

Or is it standard practice to say...

page = template.render(args...)
zconn.close()
return page

Solution

  • It is standard practice to only close the connection when the request is complete, yes.

    Postpone the close to the latest possible moment. Use could use a context manager to handle the closing for you:

    from contextlib import contextmanager
    
    @contextmanager
    def zodbconn(db):
        conn = db.open()
        yield conn.root()
        conn.close()
    

    then use:

    with zodbconn(db) as zconn:
        return template.render(args....)
    

    and the connection will be closed automatically after the return statement has been processed.