Sanic + aiohttp session

Hi,

I am trying to find a better way to handle of using session.

if i change the code to assign

Is the code change is inline with best practice with handling session ?

Original code :

@app.route('/lookupApplication')
async def lookup_id(request):
async with aiohttp.ClientSession() as session:
        async with session.get(<URL>) as resp:
            resp_data = await resp.json()

if __name__ == '__main__':
    app.run(debug=True, access_log=True, before_start=init,)

Updated code :


 @stare.listener('before_server_start')
async def initialize(app, loop):
    app.ctx.httpSession = aiohttp.ClientSession()


@app.route('/lookupApplication')
async def lookup_id(request):
        async with app.ctx.httpSession.get(<URL>) as resp:
            resp_data = await resp.json()

if __name__ == '__main__':
    app.run(debug=True, access_log=True, before_start=init,)

I am not as familiar with aiohttp as I am with httpx. However, opening a session for the lifetime of the application is probably not ideal. Maybe you should do it in middleware and attach to request.ctx instead.

Appreciate your response.

setting session to request.ctx help to clear the warning.
I new to Sanic framework, I am learning about middleware.

:clap: Welcome @vishnu

Let us know if you have any questions, and feel free to post them here or join us on Discord.