Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

View schema classes data is shared between requests #1

Open
notvad opened this issue Apr 15, 2022 · 0 comments
Open

View schema classes data is shared between requests #1

notvad opened this issue Apr 15, 2022 · 0 comments

Comments

@notvad
Copy link

notvad commented Apr 15, 2022

Since schema instance is assigned to the view, the same instance is reused for every request to the view. flask-api-framework uses marshmallow.Schema.load method to deserialize passed data to a schema instance. It means that missing non-required fields, dynamically assigned attributes and other instance attributes (eg schema context) will not be re-loaded. It may lead to the situation when a view can access schema data from the previous requests.

Here is an example:

import base64
from marshmallow import Schema, fields, validates


class MySchema(Schema):
    event = fields.String()
    b64_message = fields.String()

    @validates("b64_message")
    def validates_message(self, value):
        self.context["decoded_message"] = base64.b64decode(value).decode()


# assign schema instance to the view class
s = MySchema()

# handling first request
request_data = {"event": "first_event", "b64_message": base64.b64encode("hey".encode()).decode()}
loaded_data = s.load(data=request_data)
print(s.context["decoded_message"])  # prints "hey" which is correct

# handling second request
request_data = {"event": "second_event"}
loaded_data = s.load(data=request_data)
print(s.context["decoded_message"])  # prints "hey" but a KeyError is expected

A possible solution is to assign schema class to the view and create a new schema instance every time before calling marshmallow.Schema.load.

As an alternative, marshmallow.Schema class can be extended with a custom load_new method that returns a new schema instance.

notvad added a commit to notvad/flask-api-framework that referenced this issue Apr 15, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant