简体   繁体   中英

How to pass variable from FastAPI to other class

can someone help me with my case. I have a variable that must be pass to Class to set bool from this Class. But, in my case, I can do this to set the bool, but can't pass with a variable. In the other case, I can pass my variable, but can't set my bool from this Class. I'm using FastAPI as my API.

(1) Here is my code that can pass some variable but can't set the bool:

@app.get("/predict")
def predict(
    brand: str = Query(...),
):
    e = MyModelPrediction()
    e(brand)

    result_data = {'brand': brand}
    result = {
        'data': result_data
    }
    return result

(2) This is my code that can't pass some variable but can set the bool:

@app.get("/predict")
def predict(
    brand: str = Query(...),
    prediction=Depends(MyModelPrediction())
):
    result_data = {'brand': brand}
    result = {
        'data': result_data
    }
    return result

So, this is my class:

class MyModelPrediction(object):
    model_loaded: bool = False
    print(model_loaded)

    def __call__(self, brand):
        print("Brand :", brand)
        if not self.model_loaded:
            self._load_model()
        time.sleep(1)

    def _load_model(self):
        print("Load model...")
        time.sleep(5)
        self.model_loaded = True

I want to set model_loaded to True , but also pass the variable brand from function predict . If I use method (1), the bool still False and the variable can be pass, but if I use method (2), the bool can be True but the variable not passed.

I can't test but I would expect that you are using the same default object over and over in case 2. It's a fairly common gotcha in Python.

@app.get("/predict")
def predict(
    brand: str = Query(...),
    prediction=Depends(MyModelPrediction())
):

The default value of any argument is only evaluated once, at load time, so this is exactly the same as:

tmp1 = Query(...)
tmp2 = Depends(MyModelPrediction())

@app.get("/predict")
def predict(
    brand: str = tmp1,
    prediction = tmp2
):

These are functionally identical, but it's more obvious in the second version that every call of this function will use the same default objects unless a value is explicitly provided by the caller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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