Project Warehouse Address
- Introduction to the
- The installation
- Quick start
- Advanced usage
Introduction
Flask-validate aims to provide reliable, configuration-declarative validation for Flask requests. The purpose is to make requests with invalid parameters “fail fast” and avoid “bad effects”. At the same time, we also provide error messages after validation failures, which can improve the robustness of the Web application while elegantly telling the client what “went wrong”.
Validation is comprehensive, including headers, ARgs, forms and JSON. Validation is pure, no data is injected into the Web application, and the user should fetch the request data from the native Flask API.
Flask-validate relies on WTForms and JsonSchema as the core validation components. See its documentation for details on how to use flask-validate.
Installation
Install using PIP.
pip install flask-validate
Copy the code
Quickstart
A complete example
Create an app.py file with the following contents:
from flask import Flask, jsonify, request
from flask_validate import Input, Validator, validate
from wtforms.validators import DataRequired, AnyOf
app = Flask(__name__)
validator = Validator(app, handle_errors=lambda e: (jsonify(e.errors), 400))
class MyInput(Input):
headers = {
'token': [AnyOf(
['messi'.'cr7'], message='authentication failure')]
}
args = {'name': [DataRequired(message='name is required.')]}
@app.route('/who')
@validate(MyInput)
def who(a):
return request.args.get('name')
app.run(host='127.0.0.1', port=6579)
Copy the code
Run the python app.py command to run the web application.
When the request data is invalid, the response is processed according to the user-defined handle_errors callable object. In this case, we directly return the verification error information through JSON.
$ curl -s http://127.0.0.1:6579/who | json_pp
{
"headers" : {
"token" : [
"authentication failure"]},"query_string" : {
"name" : [
"name is required."]}}Copy the code
Only when the requested data is fully valid will the corresponding view_func process the business logic.
$ curl -s -H "token: messi" http://127.0.0.1:6579/who\?name\=mec
mec
Copy the code
Using JSON Schema
When we need to validate a JSON-formatted request body, we can use JSON Schema.
from flask import Flask, jsonify, request
from flask_validate import Input, Validator, validate
from flask_validate.validators import JsonSchema, ValidationError
schema = {'type': 'object'.'properties': {'name': {'type': 'string'}}}
def deny_users(form, field):
name = field.data.get('name')
if isinstance(name, str) andname ! ='mec':
raise ValidationError('user %s is denied.' % name)
class JsonInput(Input):
json = [JsonSchema(schema), deny_users]
app = Flask(__name__)
validator = Validator(app, handle_errors=lambda e: (jsonify(e.errors), 400))
@app.route('/who', methods=['POST'])
@validate(JsonInput)
def who(a):
print request.get_json(force=True)
return request.get_json(force=True).get('name')
app.run(host='127.0.0.1', port=6579)
Copy the code
When the JSON data format is invalid, specific information is returned.
$ curl -X POST -s -d '{"name":1}' -H 'Content-type: application/json' http://127.0.0.1:6579/who | json_pp
{
"json" : {
"_jsonschema" : [
"1 is not of type 'string'"]}}Copy the code
In the above example, we also used custom validation deny_Users, which allows us to define validation rules based on specific business logic.
$ curl -X POST -s -d '{"name":"mec1"}' -H 'Content-type: application/json' http://127.0.0.1:6579/who | json_pp
{
"json" : {
"_jsonschema" : [
"user mec1 is denied."]}}Copy the code
AdvancedUsage
In the example above, we define handle_errors when initializing flask_validate.Validator, which causes all routes to use the callable object for validation failures. To bind a particular processing behavior to a particular route, we can do this:
class MyInput(Input):
def handle_errors(self, e):
return '1024'
Copy the code
Note that handLE_errors defined in Input overrides the behavior passed in when flask_validate.Validator is initialized.
Of course, you can leave out the error handling mechanism and use the input.validate () and input.errors exposed by the Input object to handle themselves in view_func.