我尝试重用 HTTP 会话作为 aiohttp 文档建议
不要为每个请求创建一个会话。很可能您需要为每个应用程序创建一个会话来共同执行所有请求。
但是我与请求库一起使用的通常模式不起作用:
def __init__(self):
self.session = aiohttp.ClientSession()
async def get_u(self, id):
async with self.session.get('url') as resp:
json_resp = await resp.json()
return json_resp.get('data', {})
Run Code Online (Sandbox Code Playgroud)
然后我尝试
await client.get_u(1)
Run Code Online (Sandbox Code Playgroud)
我有错误
RuntimeError: Timeout context manager should be used inside a task
Run Code Online (Sandbox Code Playgroud)
任何 async_timeout 的解决方法都没有帮助。
另一种方法是工作:
async def get_u(self, id):
async with aiohttp.ClientSession() as session:
with async_timeout.timeout(3):
async with session.get('url') as resp:
json_resp = await resp.json()
return json_resp.get('data', {})
Run Code Online (Sandbox Code Playgroud)
但似乎每个请求都创建会话。
所以我的问题是:如何正确重用 aiohttp-session?
UPD:最小工作示例。具有以下视图的 Sanic 应用程序
import aiohttp
from sanic.views import …Run Code Online (Sandbox Code Playgroud)