我已经编写了一些代码来使用aiohttp / asyncio异步执行多个GET请求 . 之后,从结果中提取一些信息 . 我想把它放在烧瓶应用程序中 . 异步代码在通过 python script.py 执行时运行正常但是当我尝试在Flask路由中使用它时,它失败并返回错误 There is no current event loop in thread 'Thread-1' . Python 3.6,所有库都是最新的 . 任何帮助,将不胜感激!代码如下 .

注意:我已经尝试过不创建事件循环(未显示)和创建事件循环( async_get 的第二行)都不起作用 .

异步代码属于一个类,相关的方法:

@staticmethod
async def fetch(url, session):  # actually fetch the responses
    async with session.get(url) as response:
        resp = await response.read()
        return resp

@staticmethod
async def get_requests(urls, hdr, cookie):
    """
    create the list of tasks using a predefined header & cookie.
    await on gather()
    """
    tasks = []

    async with ClientSession(headers=hdr, cookies=cookie) as session:
        for url in urls:
            task = asyncio.ensure_future(FetcherClass.fetch(url, session))
            tasks.append(task)
        res = await asyncio.gather(*tasks)
    return res

def async_get(self, urls):
    """Retrieve a list of URL's
    """
    hdr, cookie = self._auth.header_cookie()
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    future = asyncio.ensure_future(FetcherClass.get_requests(urls, hdr, cookie))
    loop.run_until_complete(future)

    return future.result()

示例(工作)

fc = FetcherClass()
fc.async_get(['http://google.com', 'http://yahoo.com'])

示例,(使用Flask失败)

fc = FetcherClass()

@app.route('/example')
def interviews():
    # exception raised here
    # There is no current event loop in thread ...
    raw_data = fc.async_get(['http://google.com', 'http://yahoo.com'])
    data = transform(raw_data)
    res = Response(data, mimetype='text/csv')
    res.headers['Content-Disposition'] = 'attachment; filename=interviews.csv'
    return res


if __name__ == '__main__':
    app.run(debug=True)