【解决报错】‘async with’ outside async function
import aiohttp async with aiohttp.ClientSession() as session: async with session.get('http://httpbin.org/get') as resp: print(resp.status) print(await resp.text())
运行之后,会出现如题所示错误,解决方法为:
将async with xxx as xxx:这个结构放在async def xxx()函数内
import aiohttp import asyncio async def get_text(): async with aiohttp.ClientSession() as session: async with session.get('http://httpbin.org/get') as resp: print(resp.status) print(await resp.text()) def main(): loop = asyncio.get_event_loop() task = get_text() loop.run_until_complete(task) loop.close() if __name__ == '__main__': main()
这样就解决了这个问题