最近我一直在玩一些 python 3 异步功能。总的来说,我对 3.6 语法很满意,当然还有你获得的性能提升。ASGI
在我看来,围绕标准发展的令人兴奋的项目之一是starlette。我有一个示例应用程序正在运行,我正在从hdf5
文件中读取数据。h5py
还不支持异步 I/O。这给我留下了一个问题:我在这里所做的一切有意义吗?据我了解,这段代码毕竟是同步运行的。在异步上下文中执行 I/O 的推荐方法是什么?
async def _flow(indexes):
print('received flow indexes %s ' %indexes)
# uses h5py under the hood
gr = GridH5ResultAdmin(gridadmin_f, results_f)
t = gr.nodes.timeseries(indexes=indexes)
data = t.only('s1').data
# data is a numpy array
return data['s1'].tolist()
@app.route('/flow_velocity')
async def flow_results(request):
indexes_list = [[2,3,4,5], [6,7,8,9], [10,11,12,13]]
tasks = []
loop = asyncio.get_event_loop()
t0 = datetime.datetime.now()
for indexes in indexes_list:
print('Start getting indexes %s' % indexes)
# Launch a coroutine for each data fetch
task = loop.create_task(_flow(indexes))
tasks.append(task)
# Wait on, and then gather, all data
flow_data = await asyncio.gather(*tasks)
dt = (datetime.datetime.now() - t0).total_seconds()
print('elapsed time: {} [s]'.format(dt))
return JSONResponse({'flow_velocity': flow_data})
记录:
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
Start getting indexes "[2, 3, 4, 5]"
Start getting indexes "[6, 7, 8, 9]"
Start getting indexes "[10, 11, 12, 13]"
received flow indexes [2, 3, 4, 5]
received flow indexes [6, 7, 8, 9]
received flow indexes [10, 11, 12, 13]
elapsed time: 1.49779 [s]