简体   繁体   English

fastApi 中的 python 全局变量无法正常工作

[英]python global variable in fastApi not working as normal

I have a simple fastApi demo app which achieve a function: get different response json by calling a post api named changeResponse.我有一个简单的 fastApi 演示应用程序,它实现了一个功能:通过调用名为 changeResponse 的 post api 获取不同的响应 json。 The changeResponse api just changed a global variable, another api return different response through the same global variable.On local env,it works correctly, but the response always changed after i just call changeResponse once when i build this on docker.The code is as follows: changeResponse api 只是更改了一个全局变量,另一个 api 通过同一个全局变量返回了不同的响应。在本地环境中,它工作正常,但是在我在 docker 上构建它时,我只调用 changeResponse 一次后响应总是改变。代码如下如下:

from typing import Optional
from fastapi import FastAPI
from util import read_json
import enum

app = FastAPI()

type = "00"
    
@app.post("/changeResponse")
async def handle_change_download_response(param:Optional[str]):
        global type
        type = param
        print("type is "+type)
        return {"success":"true"}

@app.post("/download")
async def handle_download(param:Optional[str]):
    print("get download param: "+param)
    if legalDownload(param):
        print("type is "+type)
        return read_json.readDownloadSuccessRes(type)
    else:
        return read_json.readDownloadFailRes()

def legalDownload(data:str)->bool:
    return True

the dockerfile is as follows: dockerfile 如下:

FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7

COPY ./app /app

what i except: call changeResponse param is 7, get response for 7, call changeResponse param is 8, get response for 8. what i get: call changeResponse param is 7,get reponse for 7,call changeReponse 8, sometime the response is 7, sometime is 8,impossible to predict我除了:调用changeResponse 参数是7,得到7 的响应,调用changeResponse 参数是8,得到8 的响应。我得到的是:调用changeResponse 参数是7,得到7 的响应,调用changeReponse 8,有时响应是7 ,有时是 8,无法预测

tiangolo/uvicorn-gunicorn-fastapi is based on uvicorn-gunicorn-docker image, which by defaults creates multiple workers. tiangolo/uvicorn-gunicorn-fastapi基于uvicorn-gunicorn-docker镜像,默认情况下会创建多个 worker。 Excerpt from gunicorn_conf.py :摘自gunicorn_conf.py

default_web_concurrency = workers_per_core * cores

Thus, the described situation arises because the request is processed by different workers (processes).因此,之所以会出现上述情况,是因为请求是由不同的工作人员(进程)处理的。 Each of which has its own copy of the global variable每个都有自己的全局变量副本

Update: If you want to change the count of workers, use the following environment variables:更新:如果要更改工作人员的数量,请使用以下环境变量:

  • WORKERS_PER_CORE : It will set the number of workers to the number of CPU cores multiplied by this value. WORKERS_PER_CORE :它将工作程序的数量设置为 CPU 内核数乘以该值。
  • MAX_WORKERS : You can use it to let the image compute the number of workers automatically but making sure it's limited to a maximum. MAX_WORKERS :您可以使用它让图像自动计算工作人员的数量,但要确保将其限制为最大值。
  • WEB_CONCURRENCY Override the automatic definition of number of workers. WEB_CONCURRENCY覆盖工人数量的自动定义。

You can set it like:您可以将其设置为:

docker run -d -p 80:80 -e WEB_CONCURRENCY="2" myimage

A more detailed description of these variables and examples here 此处更详细地描述这些变量和示例


If you want to share data between workers, pay attention to this topic .如果要在 worker 之间共享数据,请关注此主题

Had the same issue and got is fixed without changing the workers.有同样的问题,在不改变工人的情况下得到了解决。

app = FastAPI()

app.type = "00"

Which I think is the best option.我认为这是最好的选择。

Ref with many thanks : enter link description here非常感谢参考:在此处输入链接描述

I already known why:我已经知道原因了:

the fastapi use uvicorn run the app, and use gunicorn to manage these uvicorn the gunicorn in docker container default starts 2*num_of_core + 1 workers to run these uvicorn,so i assume there are three app in the server,and the request was sented to random worker to handle. fastapi 使用 uvicorn 运行应用程序,并使用 gunicorn 管理这些 uvicorn docker 容器中的 gunicorn 默认启动 2*num_of_core + 1 个工作人员来运行这些 uvicorn,所以我假设服务器中有三个应用程序,并且请求被发送到随机工人处理。 that's why the response is random reference: https://docs.gunicorn.org/en/stable/design.html这就是为什么响应是随机引用的原因: https : //docs.gunicorn.org/en/stable/design.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM