最近一直在閱讀有關(guān) python 并發(fā)的內(nèi)容 realpython - python concurrency我的主要關(guān)注asyncio點是相當(dāng)新的。執(zhí)行異步活動的代碼塊使用asyncio并aiohttp在直接運行時運行良好。但是,當(dāng)我將代碼添加到我的燒瓶藍(lán)圖時,它會引發(fā)此錯誤:RuntimeError: There is no current event loop in thread 'Thread-2'出于演示目的,我制作了一個演示燒瓶應(yīng)用程序。萬一有人想測試一下。main.pyfrom flask import Flaskfrom my_blueprint import my_blueprint#Define flask appapp = Flask(__name__)#load blueprintsapp.register_blueprint(my_blueprint,url_prefix='/demo')#start flaskif __name__ == '__main__': app.run(debug=True)my_blueprint.pyfrom flask import Blueprint,request, jsonify,abort,make_responsefrom flask import make_responseimport asyncioimport timeimport aiohttpmy_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
1 回答

牧羊人nacy
TA貢獻(xiàn)1862條經(jīng)驗 獲得超7個贊
編輯:看起來你的代碼是正確的。我習(xí)慣寫不同的。但是您可能正在運行 Windows 和 Python 3.8。這只是改變了 Windows 上 python 3.8 中的默認(rèn)事件循環(huán)策略,而且它很容易出錯。您可以改回舊的事件循環(huán)策略:
改變:
asyncio.get_event_loop().run_until_complete(download_all_sites(sites))
進(jìn)入:
asyncio.set_event_loop(asyncio.SelectorEventLoop())
asyncio.get_event_loop().run_until_complete(download_all_sites(sites))
添加回答
舉報
0/150
提交
取消