我目前正在用 aiohttp
做我的第一个“婴儿学步” (来自 requests
模块)。
我尝试稍微简化请求,这样我就不必在主模块中为每个请求使用上下文管理器。
因此我尝试了这个:
async def get(session, url, headers, proxies=None):
async with session.get(url, headers=headers, proxy=proxies) as response:
response_object = response
return response_object
但结果是:
<class 'aiohttp.client_exceptions.ClientConnectionError'> - Connection closed
请求在上下文管理器中可用。当我尝试在上述函数的上下文管理器中访问它时,一切正常。
但是它不应该也可以保存在变量<response_object>
中吗?然后返回,以便我可以在上下文管理器之外访问它?
有什么解决方法吗?
最佳答案
如果您不关心在 get
方法期间加载的数据,也许您可以尝试将其加载到其中:
async def get(session, url, headers, proxies=None):
async with session.get(url, headers=headers, proxy=proxies) as response:
await response.read()
return response
使用正文是这样的:
resp = get(session, 'http://python.org', {})
print(await resp.text())
在底层,read
方法将主体缓存在名为 _body
的成员中,当尝试调用 json
时,aiohttp 首先检查是否正文是否已读。
关于python - aiohttp/从上下文管理器中获取响应对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68693855/