I'm setting up an aiohttp server using aiohttp_session to store data into an EncryptedCookieStorage. I use it to store a 7-days valid token, along with the expiration date and a refresh token. I want, no matter which endpoint the client is accessing, to check if the token (stored in the session) needs some refreshment. The choice of a middleware was pretty obvious.
The problem is, when I call await aiohttp_session.get_session(request), I'm getting a nice RuntimeError asking me to setup the aiohttp_session middleware to the aiohttp.web.Application. My guess is that my custom middleware was called before the one handling the session loading, thus the session is not accessible yet. I've searched for some "priority" system regarding middlewares, but haven't found anything.
My server is set up in a main.py file like :
def main():
app = web.Application()
middleware.setup(app)
session_key = base64.urlsafe_b64decode(fernet.Fernet.generate_key())
aiohttp_session.setup(app, EncryptedCookieStorage(session_key))
# I have tried swapping the two setup functions
web.run_app(app)
if __name__ == '__main__':
main()
Where the middleware.setup() is in a separate package, in the __init__.py :
# For each python file in the package, add it's middleware function to the app middlewares
def setup(app):
for filename in listdir('middleware'):
if filename[-2:] == 'py' and filename[:2] != '__':
module = __import__('rpdashboard.middleware.' + filename[:-3], fromlist=['middleware'])
app.middlewares.append(module.middleware)
And finally, the middleware I want to get the session in is :
@web.middleware
async def refresh_token_middleware(request, handler):
session = await get_session(request)
if session.get('token'):
pass # To be implemented ...
return await handler(request)
middleware = refresh_token_middleware
The execution issues here :
# From aiohttp_session
async def get_session(request):
session = request.get(SESSION_KEY)
if session is None:
storage = request.get(STORAGE_KEY)
if storage is None:
# This is raised
raise RuntimeError(
"Install aiohttp_session middleware "
"in your aiohttp.web.Application")
As I was saying earlier, it seems like the session is not meant to be accessed in a middleware, and isn't loaded yet. So how would I prevent my custom middleware to run before the session loading one ? Or maybe simply run manually the aiohttp_session middleware myself ? Is it even possible ?
Thanks for any feedback !
from Is it possible to access a session (from aiohttp_session) within a middleware?
No comments:
Post a Comment