python - flask 异步 aiohttp - RuntimeError : There is no current event loop in thread 'Thread-2'

标签 python multithreading flask python-asyncio aiohttp

最近在看python并发realpython - python concurrency
我的主要关注点asyncio所以我很新。
使用 asyncio 执行异步事件的代码块和 aiohttp直接运行时运行良好。
但是,当我将代码添加到我的 flask 蓝图时,它会引发此错误:

RuntimeError: There is no current event loop in thread 'Thread-2'


出于演示目的,我制作了一个演示 flask 应用程序。万一有人想测试一下。
主文件
from flask import Flask
from my_blueprint import my_blueprint

#Define flask app
app = Flask(__name__)

#load blueprints
app.register_blueprint(my_blueprint,url_prefix='/demo')

#start flask
if __name__ == '__main__':
    app.run(debug=True)
我的蓝图.py
from flask import Blueprint,request, jsonify,abort,make_response
from flask import make_response
import asyncio
import time
import aiohttp

my_blueprint = Blueprint('my_blueprint', __name__)

@my_blueprint.route('/',methods=['GET'])
def home():
    #code block
    async def download_site(session, url):
        async with session.get(url) as response:
            print("Read {0} from {1}".format(response.content_length, url))


    async def download_all_sites(sites):
        async with aiohttp.ClientSession() as session:
            tasks = []
            for url in sites:
                task = asyncio.ensure_future(download_site(session, url))
                tasks.append(task)
            await asyncio.gather(*tasks, return_exceptions=True)

    sites = ["https://www.jython.org","http://olympus.realpython.org/dice"]*20
    start_time = time.time()
    asyncio.get_event_loop().run_until_complete(download_all_sites(sites))
    duration = time.time() - start_time
    return jsonify({"status":f"Downloaded {len(sites)} sites in {duration} seconds"})
    #end of code block

最佳答案

编辑:
看起来你的代码是正确的。我习惯写不同的。
但是您可能正在运行 windows 和 python 3.8。这只是在 Windows 上更改了 python 3.8 中的默认事件循环策略,而且它非常有问题。您可以改回旧的事件循环策略:
改变:

asyncio.get_event_loop().run_until_complete(download_all_sites(sites))
进入:
asyncio.set_event_loop(asyncio.SelectorEventLoop())
asyncio.get_event_loop().run_until_complete(download_all_sites(sites))

关于python - flask 异步 aiohttp - RuntimeError : There is no current event loop in thread 'Thread-2' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62620685/

相关文章:

python - 在网络中有效识别给定距离内的祖先/后代

python - 将 Bash 变量读入 Python 脚本

c# - 发布/订阅架构

python - Flask View 引发 TypeError : 'bool' object is not callable

python - 用python进行简单的ascii url编码

python - 如何将整数 ndarray 转换为字符串并向 < 10 的元素添加前导 0

java - 如何从父线程中注意到异常?

python - 使用 Python,如何在后台等待按键时在前台运行循环?

python - Flask-Restful 中的中止方法忽略 CORS 选项

post - nginx 不会将 POST 数据转发到 uwsgi -- [更新] Flask 不会读取 POST 数据