[英]Flask asyncio aiohttp - RuntimeError: There is no current event loop in thread 'Thread-2'
Lately been reading about python concurrency realpython - python concurrency最近一直在阅读有关 python 并发realpython - python 并发
My main focus asyncio
so am fairly new.我的主要关注点
asyncio
所以相当新。
The code block that performs asynchronous activities using asyncio
and aiohttp
runs fine when run it directly.使用
asyncio
和aiohttp
执行异步活动的代码块在直接运行时运行良好。
However when i add the code to my flask blueprint it raises this error:但是,当我将代码添加到我的 flask 蓝图时,它会引发此错误:
RuntimeError: There is no current event loop in thread 'Thread-2'
For demonstration purposes i made a demo flask app.出于演示目的,我制作了一个演示 flask 应用程序。 In case anyone wants to test it out.
万一有人想测试一下。
main.py主文件
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)
my_blueprint.py我的蓝图.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
EDIT: It looks like your code was correct.编辑:看起来您的代码是正确的。 I am used to writing it different.
我习惯写不同的。 But you are probably running windows and python 3.8.
但是您可能正在运行 windows 和 python 3.8。 that just changed the default event loop policy in python 3.8 on windows and it pretty buggy.
这只是更改了 windows 上 python 3.8 中的默认事件循环策略,而且它非常有问题。 You can change back the old event loop policy:
您可以改回旧的事件循环策略:
change:改变:
asyncio.get_event_loop().run_until_complete(download_all_sites(sites))
into:进入:
asyncio.set_event_loop(asyncio.SelectorEventLoop())
asyncio.get_event_loop().run_until_complete(download_all_sites(sites))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.