python - Flask asyncio aiohttp - RuntimeError:线程'Thread-2'中没有当前事件循环
问题描述
最近在看python并发realpython——python并发
我的主要关注asyncio
点是相当新的。
使用执行异步活动的代码块,直接运行asyncio
时aiohttp
运行良好。
但是,当我将代码添加到我的烧瓶蓝图时,它会引发此错误:
RuntimeError: There is no current event loop in thread 'Thread-2'
出于演示目的,我制作了一个演示烧瓶应用程序。万一有人想测试一下。
主文件
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))
推荐阅读
- three.js - AR.js 和 aframe 管理我的 .gltf 位置和尺寸
- javascript - How to do component inheritance in React Native like on native platform?
- reactjs - 使用映射数据切换组件
- r - 如何从数据框名称中提取信息并基于它创建列
- here-api - HERE Map:如何知道图层的渲染状态?
- unity3d - 在 Unity 中缩小后 3d 模型变黑
- github - 如何在 github 页面中使用托管域
- web-scraping - 网络抓取 EconPapers 存储库的问题
- android - 在 Android Q 上结合 WiFi 说明符和建议 API
- karate - 将数组中任何 json 对象的键值的类型从字符串更改为浮点/双精度