flask session: how to close resources in the session

363 Views Asked by At

In each request to my flask API I'm creating a new handle to a resource. This is a potentially huge waste of performance, since these handles are pretty smart and can cache a lot of interactions. I would like to move the handle to my flask-session. But if the handles are no longer used, they need to be closed. Is this possible with a session ?

I want to move this code

# inside a flask route
with Resource_handle() as resource_handle:
    # use it

to this code

# inside a flask route
if "resource_handle" in session:
    resource_handle = session["resource_handle"]
else:
    resource_handle = Resource_handle()
    session["resource_handle"] = resource_handle

# where do I put resource_handle.close()

As far as I can see, the API doesn't cover this case. So I thought I would simply extend the existing sessions and implement my own resource handling session. But that's tricky, there is no end_session callback. Only open_session and save_session. The source is here: https://github.com/fengsp/flask-session/blob/master/flask_session/sessions.py

Not related to flask-sessions but to make the question more precise: I can't simply make the handle global and have all requests share it. This is a design question, I need the individual handles not to influence each other. (Plus there is the question of thread-safety. Pretty sure those handles are NOT thread-safe).

0

There are 0 best solutions below