Open
Description
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.
Metadata
Metadata
Assignees
Labels
No labels