- Schema.dump and Schema.load
The Schema.dump () method returns an Marshresult object, marshmallow the official API says that the dump and load methods return all Dict objects, but to view the source code, the Marshresult object is a namedtuple.
# # marshmallow::schema.py
# # # line 25 # #
#: Return type of:meth: ' Schema.dump ' including serialized data and ErrorsMarshalresult = Namedtuple ('Marshalresult', ['Data','Errors'])#: Return type of:meth: ' Schema.load ', including deserialized data and errorsUnmarshalresult = Namedtuple ('Unmarshalresult', ['Data','Errors'])
When I was running the official example, there was a problem here.
try : Data = Quote_schema.load (json_data) except ValidationError as err: return jsonify (err.messages), 422 First, last = Data[ " author " ][ " first " ], Data[ " author " Span style= "COLOR: #800000" > "][" last "] # code error here, typeerror:tuple indices must be integers or slices, not str
Namedtuple cannot access object information by means of result[' data ' [' xxx ']
But through result.data[' xxx '] is OK. The way to ask Namedtuple in Python doc is "." Access. It seems to be understood that name is a attribute of namedtuple,
>>>#Basic Example>>> point = Namedtuple (' Point', ['x','y'])>>> p = Point (one, y=22)#instantiate with positional or keyword arguments>>> x, y = P#unpack like a regular tuple>>>x, Y (11, 22)>>> p.x + p.y # fields also accessible by name33>>> P#readable __repr__ with a name=value stylePoint (x=11, y=22)
[Python] Marshmallow Code