异步使用 authlib 的 httpx 客户端的例子

问题描述

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

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

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

用户警告:未关闭 。详情见https://www.python-httpx.org/async/#opening-and-closing-clients

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

运行时错误:事件循环已关闭

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

解决方法

authlibAsyncOAuth2Client 继承自 httpxAsyncClient,因此您应该能够使用 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()

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...