📚

Flaskでのバリデーション

1 min read

以下ではCerberusを紹介。

https://docs.python-cerberus.org/en/stable/index.html
from flask import Flask, request
from cerberus import Validator

app = Flask(__name__)

@app.route('/products', methods=['POST'])
def create_product():
    params = {}
    params['product_name'] = request.json['product_name']
    params['price'] = request.json['price']

    schema = {
        'product_name': {
            'type': 'string',
            'required': True
        },
        'price': {
            'type': 'integer',
            'required': True
        }
    }
    v = Validator(schema)
    if v.validate(params):
        pass
    else:
        return 'validation failed', 400

Discussion

ログインするとコメントできます