如何创建单个aiohttp.ClientSession?
aiohttp推荐一个app使用一个clientsession,但是clientsession无法在协程外声明,那我怎么在不同的协程使用同一个clientsession呢?
回答:
import aiohttpimport asyncio
class MySession:
_session = None
@classmethod
def session(cls):
if not cls._session:
cls._session = aiohttp.ClientSession()
return cls._session
@classmethod
def close(cls):
return cls._session.close()
async def get_sth():
resp = await MySession.session().get('http://httpbin.org/get')
print(await resp.text())
async def close_session():
await MySession.close()
# before start your app
loop = asyncio.get_event_loop()
loop.run_until_complete(get_sth())
# ...
# after stop your app
loop.run_until_complete(close_session())
以上是 如何创建单个aiohttp.ClientSession? 的全部内容, 来源链接: utcz.com/p/937636.html