Kay Ashaolu - Instructor
Aishwarya Sriram - TA
Understanding and Handling Errors
def divide(dividend, divisor):
if divisor == 0:
raise ZeroDivisionError("divisor cannot be zero")
return dividend / divisor
try:
result = divide(sum(grades), len(grades))
except ZeroDivisionError as e:
print("There are no grades yet in your list.")
Before:
stores = [store1, store2, ...]
After:
stores = {
store_id1: { ... },
store_id2: { ... }
}
File: db.py
stores = {}
items = {}
@app.get("/store/<string:store_id>")
def get_store(store_id):
try:
return stores[store_id]
except KeyError:
abort(404, message="Store not found.")
abort
function from Flask-Smorest from flask_smorest import abort
abort(404, message="Store not found.")
@app.delete("/item/<string:item_id>")
def delete_item(item_id):
try:
del items[item_id]
return {"message": "Item deleted."}
except KeyError:
abort(404, message="Item not found.")
/items
, /stores
) requirements.txt
docker run -dp 5005:5000 -v "$PWD":/app flask-smorest-api
/app
from flask.views import MethodView
from flask_smorest import Blueprint
blp = Blueprint("stores", __name__, description="Operations on stores")
@blp.route("/store/<string:store_id>")
class Store(MethodView):
def get(self, store_id):
# Retrieve store logic
pass
def delete(self, store_id):
# Delete store logic
pass
from flask_smorest import Api
from resources.item import blp as ItemBlueprint
from resources.store import blp as StoreBlueprint
api = Api(app)
api.register_blueprint(ItemBlueprint)
api.register_blueprint(StoreBlueprint)
from marshmallow import Schema, fields
class ItemSchema(Schema):
id = fields.Str(dump_only=True)
name = fields.Str(required=True)
price = fields.Float(required=True)
store_id = fields.Str(required=True)
@blp.arguments
to validate incoming JSON data@blp.arguments(ItemSchema)
def post(self, item_data):
# Process validated data
pass
@blp.response
to format outgoing responses@blp.response(200, ItemSchema)
def get(self, item_id):
# Return item serialized by ItemSchema
pass
many=True
@blp.response(200, ItemSchema(many=True))
def get(self):
return list(items.values())
/swagger-ui
Bringing together serialization and deserialization
# resources/item.py
from flask.views import MethodView
from flask_smorest import Blueprint, abort
import uuid
from schemas import ItemSchema, ItemUpdateSchema
# In-memory storage for demonstration
items = {}
blp = Blueprint("items", __name__, description="Operations on items")
@blp.route("/item/<string:item_id>")
class Item(MethodView):
@blp.response(200, ItemSchema)
def get(self, item_id):
try:
return items[item_id]
except KeyError:
abort(404, message="Item not found.")
@blp.arguments(ItemUpdateSchema)
@blp.response(200, ItemSchema)
def put(self, item_data, item_id):
try:
item = items[item_id]
except KeyError:
abort(404, message="Item not found.")
item.update(item_data)
return item
def delete(self, item_id):
try:
del items[item_id]
return {"message": "Item deleted."}
except KeyError:
abort(404, message="Item not found.")
@blp.route("/item")
class ItemList(MethodView):
@blp.response(200, ItemSchema(many=True))
def get(self):
return list(items.values())
@blp.arguments(ItemSchema)
@blp.response(201, ItemSchema)
def post(self, item_data):
item_id = uuid.uuid4().hex
item = {**item_data, "id": item_id}
items[item_id] = item
return item
Deserialization:
ItemSchema
or ItemUpdateSchema
Serialization:
Blueprints & MethodViews: