I'm learning Flask while I'm working on a project. I'm not new to Python, but my experience mostly extends to smallish utility scripts etc. so this is something a bit larger than I'm used to with Python. I've got more experience working with Java, and in that language with a web server project I would be familiar with initializing multiple thread safe clients for various services and holding onto the references in memory, for use by all server requests (because they're thread safe).
I have a similar need in my Flask project and I've come across a recommended pattern using the global g
variable that looks like this:
@app.before_request
def before_request():
if not hasattr(g, 'my_client'):
g.my_client = the_service.get_the_client()
...which initializes the client. I have some logging in that client initialization, and every time a request passes through the server for any reason, it appears that my client is being initialized again every time. I shouldn't be surprised by this because the docs do say that the context of the global g
is limited to each request and only lasts as long as the request does.
This kind of data is not really what you would store in a session or database, so that kind of persistence doesn't seem appropriate or possible. Is it possible then for Flask?, Werkzeug? to hold onto a reference to some object that is potentially expensive to create/initialize and share it between server requests? Does it just have to be created new for every request?