带有aiohttp持久会话的RuntimeError

时间:2019-03-15 07:57:44

标签: python aiohttp

我刚开始使用aiohttp时遇到了一个似乎无法解决的问题。

我创建一个持久会话。

session = aiohttp.ClientSession(headers=headers)

async def fetch(url):
    async with session.get(url) as resp:
        return await resp.json()

async def run():
    task = asyncio.create_task(fetch('https://someurl'))
    await task

当我调用run()时,我的程序由于跟踪而崩溃。

RuntimeError: Timeout context manager should be used inside a task

我没有任何回溯,当我不使用持久性会话时,func可以很好地执行。也就是说,当我如下定义run时,fetch会按预期执行。

async def fetch(url):
    async with aiohttp.ClientSession(headers=headers) as see:
        async with session.get(url) as resp:
            return await resp.json()

1 个答案:

答案 0 :(得分:0)

您需要将session = ...ClientSession移到fetch内部,创建会话时最好使用async with

类似

async def fetch(url):
    async with aiohttp.ClientSession(headers=headers) as session:
        async with session.get(url) as resp:
            return await resp.json()

async def run():
    task = asyncio.create_task(fetch('https://someurl'))
    await task

已更新的更完整的示例:

class Foboar():
    def __init__(self):
        self.session = None

    async def run(self):
        self.session = aiohttp.ClientSession(headers=headers)
        try:
            for url in all_my_urls:
                await self.fetch(url)
        finally:
            await self.session.close()

    async def fetch(self, url):
        async with self.session.get(url) as resp:
            return await resp.json()