0

I have a simple Flask api where I'm trying to construct a class based on the request json body. Its important that the requests are independent from each other.

However, I've found that the requests are not independent of each other.

The first request I make to the api works as expected: enter image description here

But an interesting thing happens when I make another request! enter image description here

Somehow bob the builder is persisting between requests and living in the allStoreManagers variable.

Can someone help me figure out why this is happening?

Code Link (its only 3 files, don't worry)

Python Version: Python 3.8

Dependencies: Flask

Files:

api.py

from flask import Flask, request

api = Flask(__name__)


@api.route("/create_store", methods=["POST"])
def tbd():
    from furniture_class import FancyFurnitureStore

    kwargs = request.json
    my_store = FancyFurnitureStore(**kwargs)

    return my_store.to_dict()


if __name__ == "__main__":
    api.run(host="127.0.0.1", port=8080, debug=True)

furniture_class.py

class FancyFurnitureStore:
    def __init__(
        self,
        storeManager: str,
        allStoreManagers: dict = {},
        version: int = 1,
        **kwargs,
    ):
        self.version = version
        self.storeManager = storeManager

        # allStoreManagers should initialize to {} every time right??
        self.allStoreManagers = allStoreManagers

        if str(self.version) not in self.allStoreManagers.keys():
            self.allStoreManagers[str(self.version)] = self.storeManager

    def to_dict(self):
        return self.__dict__

Final thoughts:

  • If I don't put the class in a separate file and keep everything on api.py, the requests are independent from each other. Weird. Why would putting the class in a different file cause problems?
  • The allStoreManagers variable is somehow not defaulting to {} and instead has the dictionary of the first request in it. Restarting the api clears the variable but it just gets stuck again on the subsequent request.
davidism
  • 121,510
  • 29
  • 395
  • 339
Tim Estes
  • 377
  • 2
  • 19

1 Answers1

1

The allStoreManagers variable is somehow not defaulting to {} and instead has the dictionary of the first request in it.

This is intended behaviour of default values given to Python parameter variables. This can be confusing when coming from different languages, but in Python those default values are evaluated once, at function definition, not at function call.

The way to get a different dictionary instance at each call, is to use None as default, and add a line of code:

    def __init__(
        self,
        storeManager: str,
        allStoreManagers: None,
        version: int = 1,
        **kwargs,
    ):
        if dict is None:
            dict = {}
        # ...etc
trincot
  • 317,000
  • 35
  • 244
  • 286