aiohttp session 在不退出上下文管理器的情况下关闭
aiohttp session closed without exiting the context manager
我有一个非常复杂的 API,带有自定义参数和 headers,所以我创建了一个 class 来环绕它。这是一个人为的例子:
import asyncio
import aiohttp
# The wrapper class around my API
class MyAPI:
def __init__(self, base_url: str):
self.base_url = base_url
async def send(self, session, method, url) -> aiohttp.ClientResponse:
request_method = getattr(session, method.lower())
full_url = f"{self.base_url}/{url}"
async with request_method(full_url) as response:
return response
async def main():
api = MyAPI("https://httpbin.org")
async with aiohttp.ClientSession() as session:
response = await api.send(session, "GET", "/uuid")
print(response.status) # 200 OK
print(await response.text()) # Exception: Connection closed
asyncio.run(main())
为什么我的 session 关闭了?我没有退出 session
.
的上下文管理器
如果我忽略包装器 class,一切都会按预期工作:
async def main():
async with aiohttp.ClientSession() as session:
async with session.get("https://httpbin.org/uuid") as response:
print(await response.text())
离开 request_method(full_url)
上下文后,您将无法调用 response.text()。
如果你写:
async with request_method(full_url) as response:
text = await response.text()
return response.status, text
然后send()
方法returns没有错误。
我有一个非常复杂的 API,带有自定义参数和 headers,所以我创建了一个 class 来环绕它。这是一个人为的例子:
import asyncio
import aiohttp
# The wrapper class around my API
class MyAPI:
def __init__(self, base_url: str):
self.base_url = base_url
async def send(self, session, method, url) -> aiohttp.ClientResponse:
request_method = getattr(session, method.lower())
full_url = f"{self.base_url}/{url}"
async with request_method(full_url) as response:
return response
async def main():
api = MyAPI("https://httpbin.org")
async with aiohttp.ClientSession() as session:
response = await api.send(session, "GET", "/uuid")
print(response.status) # 200 OK
print(await response.text()) # Exception: Connection closed
asyncio.run(main())
为什么我的 session 关闭了?我没有退出 session
.
如果我忽略包装器 class,一切都会按预期工作:
async def main():
async with aiohttp.ClientSession() as session:
async with session.get("https://httpbin.org/uuid") as response:
print(await response.text())
离开 request_method(full_url)
上下文后,您将无法调用 response.text()。
如果你写:
async with request_method(full_url) as response:
text = await response.text()
return response.status, text
然后send()
方法returns没有错误。