I'm working on an async Flask application and have a custom object that initializes with request data. Here is a simplified version of my code:
In my route handler:
@app.route('/')
async def unified_route():
async with UserHandler() as handler:
page_html = await handler.render('index.html')
return await handler.finish(page_html)
In the initialization of UserHandler:
class UserHandler:
def __init__(self):
self.cookies = None
async def __aenter__(self):
self.cookies = request.cookies
return self
async def render(self, template_name):
return f"Rendered {template_name}"
async def finish(self, page_html):
return page_html
UserHandler is located in another file and imports request from Flask.
My question is:
Will this approach work correctly, given that request is not passed directly but imported within UserHandler? Can this lead to any issues with user data being mixed up in concurrent requests?
ChatGPT wrote that Flask uses context objects to manage request data and should handle concurrent requests correctly, even with async functions, as long as Flask is properly managing the request context.
I have some distrust of this, since the global request class with content coming from the context sounds unreliable, and the bot itself sometimes makes mistakes.