【发布时间】:2018-11-09 15:16:01
【问题描述】:
我想创建一个使用 aiohttp 进行 API 调用的调度程序类。我试过这个:
import asyncio
import aiohttp
class MySession:
def __init__(self):
self.session = None
async def __aenter__(self):
async with aiohttp.ClientSession() as session:
self.session = session
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
if self.session:
await self.session.close()
async def method1():
async with MySession() as s:
async with s.session.get("https://www.google.com") as resp:
if resp.status == 200:
print("successful call!")
loop = asyncio.get_event_loop()
loop.run_until_complete(method1())
loop.close()
但这只会导致错误:RuntimeError: Session is closed。
__aenter__ 函数的第二种方法:
async def __aenter__(self):
self.session = aiohttp.ClientSession()
return self
效果很好。这是一个好的构造吗?它不遵守如何使用 aiohttp 的示例。还想知道为什么第一种方法不起作用?
【问题讨论】:
标签: python python-asyncio aiohttp