I need to use an HTTP client in my Azure Function. I can use aiohttp like this (this is a minimalistic example form the MSFT documentation).
import aiohttp
import azure.functions as func
async def main(req: func.HttpRequest) -> func.HttpResponse:
async with aiohttp.ClientSession() as client:
async with client.get("URL") as response:
return func.HttpResponse(await response.text())
return func.HttpResponse(body='NotFound', status_code=404)
However, this creates a new session object for each request, which should be avoided, as per the aiohttp documentation, as it’s an expensive operation.
My question is – how can I instantiate a session object once and share it between function calls? From the ClientSession
code, it looks like __aenter__
doesn’t do anything, so I could instantiate the session just by calling session = aiohttp.ClientSession()
. However, where would I call __aexit__
?
Or is there even a better way to instantiate and clean up global objects in Azure Functions that require async instantiation and clean-up?