【问题标题】:How to use FastAPI and Spacy together to handle multiple requests in parallel如何同时使用 FastAPI 和 Spacy 并行处理多个请求
【发布时间】:2021-01-08 08:02:33
【问题描述】:

我正在使用 spacy 和 FastAPI 来处理一些 nlp 任务的请求。当 API 启动并使用该模型提供请求时,我正在加载 spacy 大型模型。我看到的是多个请求的时间随着并行请求的数量线性增加。如何将 spacy 与 FastAPI 集成,以便在不增加时间的情况下同时处理多个请求。我有一个 4 核 CPU,单个请求大约需要 4 毫秒。我想在 4 毫秒内同时处理 4 个请求。

【问题讨论】:

  • 难道 spacy 没有克服 GIL 并阻止每个请求?
  • 您可以尝试对 NLP 使用多处理,以利用所有 cpu 内核。使用 FastApi 进行多处理的示例here

标签: python spacy fastapi


【解决方案1】:

对 Spacy 不是很熟悉,但一般来说,如果你有阻塞代码,你应该把它放到一个非异步路由 def 中。这是因为 FastAPI 会将对该路由的调用放入线程池中。

https://fastapi.tiangolo.com/async/#path-operation-functions

@app.get("/blocking")
def blocks():
    # do something blocking
    pass

你也可以试试fastapi的后台任务(https://fastapi.tiangolo.com/tutorial/background-tasks/)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-19
    • 2015-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2017-06-29
    • 2021-12-21
    相关资源
    最近更新 更多