David Blume's GitList
Repositories
testpython.git
Code
Commits
Branches
Tags
Search
Tree:
6b56198
Branches
Tags
main
python2
testpython.git
bored
bored.py
Add a dataclass and datavalidation, add Path example.
David Blume
commited
6b56198
at 2021-04-04 12:41:39
bored.py
Blame
History
Raw
#!/usr/bin/env python3 #from https://python.plainenglish.io/taming-your-python-dictionaries-with-dataclasses-marshmallow-and-desert-388dbffedaec from dataclasses import dataclass import json from marshmallow import EXCLUDE, fields, post_load, Schema, validate import requests @dataclass class Activity: activity: str participants: int price: float class ActivitySchema(Schema): activity = fields.Str(required=True) participants = fields.Int( required=True, validate=validate.Range(min=1, max=50, error="Participants must be between 1 and 50 people") ) price = fields.Float( required=True, validate=validate.Range(min=0, max=1, error="Price must be between $1 and $100") ) @post_load def transform_price(self, data, **kwargs): # The `price` key always has the price between 0 and 1 for some reason so # let's convert that number into dollars data['price'] = data['price'] * 100 return data def get_activity() -> Activity: resp = requests.get("https://www.boredapi.com/api/activity").json() validated_resp = ActivitySchema(unknown=EXCLUDE).load(resp) return Activity( activity=validated_resp["activity"], participants=validated_resp["participants"], price=validated_resp["price"] ) if __name__ == '__main__': print(get_activity())