Learning WSGI; I'm trying to create a WSGI app that:
- caches state across a bunch of requests
- opens a single autocommit database connection for a bunch of requests
- creates a cursor to deal with each request
So,
class RequestHandler:
def __init__(self, app, environ, start_response, cursor):
self.start_response = start_response
self.cursor = cursor
def __iter__(self):
self.start_response('200 OK', [('Content-type','text/plain')])
yield do_stuff_with(self.cursor)
def close(self):
self.cursor.close()
class Application:
def __init__(self):
self.connection = psycopg2.connect(database="site", user="www-data")
self.connection.set_isolation_level(0)
def __call__(self, environ, start_response):
return RequestHandler( self, environ, start_response, self.connection.cursor() )
So, I am able to clean up the per-request state in RequestHandler
's close()
method; what is the correct way to clean up any shared state, close the database connection etc. when the server decides it's done with the whole application? The WSGI spec doesn't seem to provide any guarantees equivalent to the per-request close()
- am I missing something? Or is there some reason why this is a fundamentally misguided approach?