我正在构建一个 FastAPI 应用程序,它将为 Dask Array 的块提供服务。我想利用FastAPI 的异步功能以及Dask-distributed 的异步操作能力。下面是一个 mcve,它演示了我在应用程序的服务器端和客户端上要做什么:
服务器端:
import time
import dask.array as da
import numpy as np
import uvicorn
from dask.distributed import Client
from fastapi import FastAPI
app = FastAPI()
# create a dask array that we can serve
data = da.from_array(np.arange(0, 1e6, dtype=np.int), chunks=100)
async def _get_block(block_id):
"""return one block of the dask array as a list"""
block_data = data.blocks[block_id].compute()
return block_data.tolist()
@app.get("/")
async def get_root():
time.sleep(1)
return {"Hello": "World"}
@app.get("/{block_id}")
async def get_block(block_id: int):
time.sleep(1) # so we can test concurrency
my_list = await _get_block(block_id)
return {"block": my_list}
if __name__ == "__main__":
client = Client(n_workers=2)
print(client)
print(client.cluster.dashboard_link)
uvicorn.run(app, host="0.0.0.0", port=9000, log_level="debug")
客户端
import dask
import requests
from dask.distributed import Client
client = Client()
responses = [
dask.delayed(requests.get, pure=False)(f"http://127.0.0.1:9000/{i}") for i in range(10)
]
dask.compute(responses)
在这个设置中,compute()
调用_get_block
是“阻塞的”,一次只计算一个块。我尝试了Client(asynchronous=True)
和client.compute(dask.compute(responses)
) 的各种组合,但没有任何改进。是否可以await
计算 dask 数组?