Как сделать несколько удаленных запросов в Flask?

На SO нашёл код, который позволяет сделать несколько запросов на удаленные сайты

import aiohttp
import asyncio
import async_timeout
from flask import Flask

loop = asyncio.get_event_loop()
app = Flask(__name__)

async def fetch(url):
    async with aiohttp.ClientSession() as session, async_timeout.timeout(2):
        async with session.get(url) as response:
            return await response.text()

def fight(responses):
    return "Why can't we all just get along?"

@app.route("/")
def index():
    # perform multiple async requests concurrently
    responses = loop.run_until_complete(asyncio.gather(
        fetch("https://google.com/"),
        fetch("https://bing.com/"),
        fetch("https://duckduckgo.com"),
        fetch("http://www.dogpile.com"),
    ))

    # do something with the results
    return fight(responses)

if __name__ == "__main__":
    app.run(debug=False, use_reloader=False, host='localhost', port=5555)

При запуске пишет RuntimeError: There is no current event loop in thread 'Thread-7'. ОС Windows


Ответы (1 шт):

Автор решения: eri

loop = asyncio.get_event_loop() запушенна в основнот треде, но фласк обрабатывает запросы в отдельных потоках, где нужен отдельный event_loop.

Если сделать функцию index асинхронной, то фласк сам всё cby[hjybpetn:

@app.route("/")
async def index():
    # perform multiple async requests concurrently
    responses = await asyncio.gather(
        fetch("https://google.com/"),
        fetch("https://bing.com/"),
        fetch("https://duckduckgo.com"),
        fetch("http://www.dogpile.com"),
    )

    # do something with the results
    return fight(responses)
→ Ссылка