[英]what does a "RuntimeError: There is no current event loop in thread 'Thread-2'." error mean?
[英]Flask asyncio aiohttp - RuntimeError: There is no current event loop in thread 'Thread-2'
最近一直在閱讀有關 python 並發realpython - python 並發
我的主要關注點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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.