我有一个 FastAPI 应用程序,它在几个不同的场合需要调用外部 API。我使用 httpx.AsyncClient 进行这些调用。关键是我不完全理解我应该如何使用它。
从httpx 的文档中,我应该使用上下文管理器,
async def foo():
""""
I need to call foo quite often from different
parts of my application
"""
async with httpx.AsyncClient() as aclient:
# make some http requests, e.g.,
await aclient.get("http://example.it")
但是,我知道每次调用时都会以这种方式生成一个新客户端foo()
,而这正是我们希望通过首先使用客户端来避免的。
我想另一种方法是在某处定义一些全局客户端,并在需要时将其导入
aclient = httpx.AsyncClient()
async def bar():
# make some http requests using the global aclient, e.g.,
await aclient.get("http://example.it")
但是,第二个选项看起来有些可疑,因为没有人负责关闭会话等。
所以问题是:如何httpx.AsyncClient()
在 FastAPI 应用程序中正确(重新)使用?