Good day ladies and gents,
I would like to understand what's the "blessed" way to use aiohttp.ClientSession in real applications, particularly with regards to session life-cycle.
Most of the examples in docs create the session through context manager, and I wonder how does it map to a "real" code where you generally have a "starter" function that hooks up components together and lunches them.
E.g. if we take a simple server (not necessary aiohttp.web server) that talks to several upstream APIs:
import asyncio
import aiohttp
import settings # My project settings lib
class UpstreamObjectsClient:
def __init__(self, host, path="/objects"):
self.host = host
self.path = path
self.session = aiohttp.ClientSession()
async def get(self, obj_id):
url = "http://{}{}/{}".format(self.host, self.path, obj_id)
resp = await self.session.get(url)
resp.raise_for_status()
return await resp.json()
async def close(self):
await self.session.close()
class MyService:
def __init__(self, upstream_objects_client):
self.uoc = upstream_objects_client
async def serve(self):
# Do something useful today
pass
async def compose_and_run():
uoc = UpstreamObjectsClient(settings.host)
svc = MyService(uoc)
try:
await svc.serve()
finally:
await uoc.close()
if __name__ == "__main__":
asyncio.run(compose_and_run()) # Python 3.7
So, with regards to compose_and_run() function above - is this indeed a recommended approach? I mean I could use
async with UpstreamObjectsClient(settings.host) as uoc:
MyService(uoc).serve()
But in a real application where I can have much more services, it can become something unpretty like:
async with Svc1() as svc1:
async with Svc2() as svc2:
async with Sbc3() as svc3:
MyServer(svc1, svc2, svc3).server()
from contextlib import AsyncExitStack
async def compose_and_run():
async with AsyncExitStack as stack:
uoc = UpstreamObjectsClient(settings.host)
stack.push_async_callback(uoc.close) # Or just make UpstreamObjectsServer to work as context manager
await MyService(uoc).server()
So, what do you use? Try...finally? AsyncExitStack? Something else I didn't think of?
Thank you,
Zaar