📚

Flaskでのバリデーション

2021/06/23に公開

以下ではCerberusを紹介。
https://docs.python-cerberus.org/en/stable/index.html

from flask import Flask, request
from cerberus import Validator

app = Flask(__name__)

@app.post("/products")
def create_product():
    product = {}
    product["name"] = request.json["name"]
    product["price"] = request.json["price"]

    schema = {
        "name": {
            "type": "string",
            "required": True
        },
        "price": {
            "type": "integer",
            "required": True
        }
    }
    v = Validator(schema)
    if not v.validate(params):
        return v.errors, 400

Discussion