【问题标题】:Results Are Getting Mixed Up For Concurrent Requests in FastApi Using Gunicorn Server使用 Gunicorn 服务器的 FastApi 中的并发请求的结果混淆了
【发布时间】:2021-07-30 10:23:32
【问题描述】:

根据线程标题,给定以下 API:

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=['*'],
    allow_credentials=True,
    allow_methods=['*'],
    allow_headers=['*'],
)

app.mount("/app/static", StaticFiles(directory="app/static"), name="static")


@app.post("/")
async def get_text(image: UploadFile = File(...)):
    
    temp_file = _save_file_to_disk(image, path="app/static/", save_as="temp")
    text = await ocr(temp_file)
   
    return {"text": text}

和下面的 Gunicorn 命令来启动应用程序:

CMD ["gunicorn", "app:app", "-w", "4", "--threads", "12", "--timeout", "120", 
"--bind", "0.0.0.0:8080", "-k","uvicorn.workers.UvicornWorker", "--worker-connections", "1000"]

如果 3 个不同的请求同时由 3 个不同的用户发送,第一个用户的结果会超过第二个和第三个用户的结果

【问题讨论】:

    标签: python-3.x concurrency load-balancing gunicorn fastapi


    【解决方案1】:

    虽然您在问题中缺少相关上下文,但我将尝试猜测:

    temp_file = _save_file_to_disk(image, path="app/static/", save_as="temp")
    

    这似乎将上传的文件保存为tempapp/static 下。然后在这个文件上运行ocr

    text = await ocr(temp_file)
    

    但是 - 此文件名对于所有三个进程都是相同的,这意味着最后一个请求将使用请求 3 的内容覆盖该文件。每个进程都会开始他们的 ocr-ing,但是在进程下面的文件已经被改变了。

    而是为每个文件使用一个唯一的名称 - 而且您可能还应该将其保留在您直接通过 static 提供的任何内容之外。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 2022-12-10
      • 1970-01-01
      相关资源
      最近更新 更多