Creating a Marshmallow schema to validate, serialize, and deserialize the model

Now, we will create a simple Marshmallow schema that we will use to validate, serialize, and deserialize the previously declared SurfboardMetricModel model.

Stay in the metrics.py file in the metrics/metrics/models subfolder. Add the following lines to declare SurferStatus Enum and the SurfboardMetricSchema class. The code file for the sample is included in the restful_python_2_09_01 folder, in the Pyramid01/metrics/metrics/models/metrics.py file:

class SurferStatus(Enum): 
    IDLE = 0 
    PADDLING = 1 
    RIDING = 2 
    RIDE_FINISHED = 3 
    WIPED_OUT = 4 
 
 
class SurfboardMetricSchema(Schema): 
    id = fields.Integer(dump_only=True) 
    status = EnumField(SurferStatus, required=True) 
    speed_in_mph = fields.Integer(required=True) 
    altitude_in_feet = fields.Integer(required=True) 
    water_temperature_in_f = fields.Integer(required=True) 

First, the code declares the SurferStatus Enum that we will use to map description to an integer for the surfer status. We want the users of the API to be able to specify the status as a string that matches one of the Enum descriptions. For example, if the user wants to create a new metric with its status set to SurferStatus.PADDLING, they should use 'PADDLING' as the value for the status key in the provided JSON body.

Then, the code declares the SurfboardMetricSchema class as a subclass of the marshmallow.Schema class. We declare the attributes that represent fields as instances of the appropriate classes declared in the marshmallow.fields module. Whenever we specify the True value for the dump_only argument, it means that we want the field to be read-only. For example, we won't be able to provide a value for the id field in the schema. The value for this field will be automatically generated by the SurfboardMetricManager class.

The SurfboardMetricSchema class declares the status attribute as an instance of the marshmallow_enum.EnumField class. The enum argument is set to SurferStatus to specify that only the members of this Enum will be considered valid values. As a result of this setting, only a string that matches the descriptions in SurferStatus Enum will be accepted as a valid value for this field during deserialization. In addition, whenever this field is serialized, the string representation of the Enum description will be used.

The speed_in_mph, altitude_in_feet, and water_temperature_in_f attributes are instances of the fields.Integer class, with the required argument set to True.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.59.231