Combine Flask and marshmallow for quick parameter verification

created at 07-27-2021 views: 13

How to perform parameter verification conveniently and quickly in Flask? As follows, we complete a convenient and quick parameter verification function by combining the tool functions provided by Flask and marshmallow.

from flask import abort, make_response, jsonify
from marshmallow import Schema, fields, ValidationError


def check_data(schema, data):
    try:
        return schema().load(data)
    except ValidationError as e:
        abort(make_response(jsonify(code=400, message=str(e.messages), result=None), 400))


class ReportSchema(Schema):
    app_type = fields.Int(missing=0)
    app_version = fields.Str(required=True)
    model = fields.Str(missing="Unknow")
    os_type = fields.Int(required=True)
    os_version = fields.Str(required=True)

When using, you only need to import the Schema and check_data functions, for example:

from flask import request

from schemas import (
    check_data,
    ReportSchema,
)

@app.route("/")
def get_report():
    qs_dict = check_data(ReportSchema, request.args)
    pass

@app.route("/report", methods=["POST"])
def report():
    json_dict = check_data(ReportSchema, request.get_json())
    pass

In this way, if the parameters are not satisfied, 400 will be automatically returned, and the error information will be printed in the returned JSON, and without manual return, the process will be automatically terminated through the abort function.

If the parameters are satisfied, it will be returned by the check_data function, and then only need to be used.

created at:07-27-2021
edited at: 07-27-2021: