Close a client created outside `async with`
Manual lifecycle management
HTTPX · Function
AsyncClient.aclose() asynchronously closes the client's transport and proxies. Await it when explicitly managing an AsyncClient instead of relying on an async context manager.
aclose() asynchronously shuts down the AsyncClient's transport and proxies. Await it when a client was created without an async context manager, typically after all requests have completed.
await client.aclose()None
AsyncClient, which supports asynchronous requests and connection pooling.import asyncio
import httpx
async def main():
client = httpx.AsyncClient()
try:
response = await client.get("https://example.org")
print(response.status_code)
finally:
await client.aclose()
asyncio.run(main())This creates an asynchronous client, performs a request, and explicitly releases its resources in a finally block.
Manual lifecycle management
Guaranteed cleanup
Shared asynchronous client
AsyncClient.aclose() do?Call await client.aclose() when an AsyncClient should be closed explicitly. The method closes the client's transport and proxies.
Follow-up: How can explicit cleanup be avoided? Use async with httpx.AsyncClient() as client: so the context manager closes the client when the block exits.
aclose() is asynchronous and takes only self, so it has no configuration parameters. Its documented return value is None.
Follow-up: What should code do if it needs to continue making requests? Keep the client open until all requests finish, then await aclose() once.
Use explicit closure when the client is managed outside a context-manager block, such as a longer-lived application component. Put cleanup in a finally block so it also runs when a request fails.
Follow-up: What is the simpler scoped alternative? Use an async with block around the client and perform all related requests inside it.
AsyncClientAsyncClient.__aenter__AsyncClient.__aexit__Client.close