Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Requires Marshmallow version 3 in order to raise exceptions from
- # loading
- # pip install marshmallow --pre
- from marshmallow import fields, Schema, post_load, validates, ValidationError
- class Location():
- def __init__(self, latitude: float, longitude: float) -> None:
- self.latitude = latitude
- self.longitude = longitude
- class ParkingLot():
- def __init__(self, capacity: int, name: str, price: float, location: Location) -> None:
- self.capacity = capacity
- self.name = name
- self.price = price
- self.location = location
- self.id = None
- class LocationSchema(Schema):
- latitude = fields.Float(required=True)
- longitude = fields.Float(required=True)
- class ParkingLotSchema(Schema):
- capacity = fields.Int(required=True)
- name = fields.Str(required=True)
- price = fields.Float()
- location = fields.Nested(LocationSchema, required=True)
- @validates('price')
- def validate_price(self, price: float):
- if price < 0:
- raise ValidationError("Price must be non-negative")
- @validates('capacity')
- def validate_capacity(self, capacity: int):
- if capacity < 1:
- raise ValidationError("Capacity must be positive")
- @post_load
- def build_parking_lot(self, data: dict) -> ParkingLot:
- return ParkingLot(**data)
- if __name__ == '__main__':
- schema = ParkingLotSchema()
- correct_data = {'location': {'latitude': 1.0, 'longitude': 2.0},
- 'name': 'my_parking_lot', 'capacity': 500, 'price': 1.5}
- invalid_data = {'location': {'latitude': 1.0, 'longitude': 2.0},
- 'name': 'my_parking_lot', 'capacity': -999, 'price': 1.5}
- missing_data = {'location': {'latitude': 1.0, 'longitude': 2.0},
- 'name': 'my_parking_lot', 'price': 1.5}
- missing_loc_data = {'location': {'longitude': 2.0},
- 'name': 'my_parking_lot', 'capacity': 500, 'price': 1.5}
- for data in (correct_data, invalid_data, missing_data, missing_loc_data):
- try:
- pl = schema.load(data)
- print(pl)
- except ValidationError as err:
- print(err)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement