最近读了关于Python并发的文章《Real Python - Python并发》
我的主要关注点是asyncio
,所以我还比较新手。
使用asyncio
和aiohttp
执行异步活动的代码块在直接运行时可以正常运行。
但是,当我将这段代码添加到我的Flask蓝图中时,就会引发以下错误:
RuntimeError: There is no current event loop in thread 'Thread-2'
为演示目的,我制作了一个演示Flask应用程序。 如果有人想测试它,请参考以下内容。
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
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
http://127.0.0.1:5000/demo/
时,还会出现一堆错误raise RuntimeError('Event loop is closed')
。 - xaander1