There are several examples here of using an httpx
client instead of a requests
based session with the popular oauth lib, authlib
However in those examples, they don't show how to properly open and close an async httpx
session. See https://www.python-httpx.org/async/
When I try to use it as suggested, I get warnings either about the session not being closed:
UserWarning: Unclosed <authlib.integrations.httpx_client.oauth2_client.AsyncOAuth2Client object at 0x000001B6444BFEB0>. See https://www.python-httpx.org/async/#opening-and-closing-clients for details
And if I call twice, I get
RuntimeError: Event loop is closed
This makes complete sense to me, as the examples in authlib
s docs aren't using a context manager for the async session
authlib
's AsyncOAuth2Client
inherits from httpx
's AsyncClient
, so you should be able to use the same methods given at https://www.python-httpx.org/async/#opening-and-closing-clients. So either something like:
async with authlib.integrations.httpx_client.oauth2_client.AsyncOAuth2Client() as client:
...
or:
client = authlib.integrations.httpx_client.oauth2_client.AsyncOAuth2Client()
...
await client.aclose()
Should allow you to open and close sessions as needed.