0

这里有几个使用httpx客户端而不是requests使用流行的 oauth 库的基于会话的示例,authlib

但是在这些示例中,它们没有显示如何正确打开和关闭异步httpx会话。见https://www.python-httpx.org/async/

当我尝试按照建议使用它时,我会收到有关会话未关闭的警告:

用户警告:未关闭 <authlib.integrations.httpx_client.oauth2_client.AsyncOAuth2Client 对象位于 0x000001B6444BFEB0>。有关详细信息,请参阅https://www.python-httpx.org/async/#opening-and-closing-clients

如果我打电话两次,我得到

RuntimeError:事件循环已关闭

这对我来说很有意义,因为authlibs 文档中的示例没有为异步会话使用上下文管理器

4

1 回答 1

1

authlib'sAsyncOAuth2Client 继承自httpx's AsyncClient,因此您应该能够使用https://www.python-httpx.org/async/#opening-and-closing-clients中给出的相同方法。所以要么像:

async with authlib.integrations.httpx_client.oauth2_client.AsyncOAuth2Client() as client:
    ...

或者:

client = authlib.integrations.httpx_client.oauth2_client.AsyncOAuth2Client()
...
await client.aclose()

应该允许您根据需要打开和关闭会话。

于 2021-05-12T18:57:21.313 回答