I have a NewRequest event handler (subscriber) in Pyramid which looks like this:
@subscriber(NewRequest)
def new_request_subscriber(event):
request = event.request
print('Opening DB conn')
// Open the DB
request.db = my_connect_to_db()
request.add_finished_callback(close_db_connection)
However, I have observed that a connection to the DB is opened even if the request goes to a static asset, which is obviously unnecessary. Is there a way, from the NewRequest handler, to check if the request is bound for a static asset? I have tried comparing the view_name to my static view’s name, but apparently the view_name attribute is not available at this early stage of processing the request.
If anyone has any interesting ideas about this, please let me know!
The brute force way is to compare the
request.pathvariable to your static view’s root, a larequest.path.startswith('/static/').The method I like the best and use in my own apps is to add a property to the
requestobject calleddbthat is lazily evaluated upon access. So while you may add it to the request, it doesn’t do anything until it is accessed.Later in your code you can access
request.db()to get the connection. Unfortunately it’s not possible to add a property to an object at runtime (afaik), so you can’t set it up so thatrequest.dbgives you what you want. You can get this behavior without using a subscriber by the cookbook entry where you subclassRequestand add your own lazy property via Pyramid’s@reifydecorator.