В последнее время я немного поигрался с асинхронными функциями Python 3.В целом, я доволен синтаксисом 3.6 и, конечно, повышением производительности, которое вы получаете.Один из захватывающих проектов, которые развиваются вокруг стандарта ASGI
, на мой взгляд, - starlette .У меня запущен пример приложения, в котором я читаю данные из файла hdf5
.h5py
пока не поддерживает асинхронный ввод-вывод.В связи с этим возникает вопрос: имеет ли смысл то, что я здесь делаю?Насколько я понимаю, этот код работает синхронно в конце концов.Каков рекомендуемый способ ввода / вывода в асинхронных контекстах?
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]