flask modify flask_wtf validation to verify that it supports json data

flask default policy is not separated front and rear ends, the front end to the delivery post, put ... etc. flask + wtf data form.

 

Now the trend is separated front and rear ends, then certain modifications of the flask, the front and rear end becomes separated, in the front end of the rear end of the page request, the request format json then there must be used to transfer data, but only supports the default flask_wtf form form, then the changes to support json

 

code show as below:

. 1  # Coding. 8 = UTF- 
2  
. 3  from Flask Import Request
 . 4  from WTForms Import Form1
 . 5  from OnlineClassroom.app.err.JsonValidateErr Import JsonValidateErr
 . 6  
. 7  
. 8  # Request Data base verifier 
. 9  class RequestBaseForm (Form1):
 10      # resolution request parameter 
. 11      DEF  the __init__ (Self):
 12 is          # TODO be treated, if the incoming request is a request form the else parameter, if the following operations json 
13 is          IF  " file application / json " in request.headers.get("Content-Type"):
14             data = request.get_json(silent=True)
15             args = request.args.to_dict()
16             super(RequestBaseForm, self).__init__(data=data, **args)
17         else:
18             # application/x-www-form-urlencoded    or    multipart/form-data
19             data = request.form.to_dict()
20             args = request.args.to_dict()
21             super(RequestBaseForm, self).__init__(the Data = the Data, ** args)
 22  
23      # of parameters validation error thrown 
24-      DEF validate_for_api (Self):
 25          ! Valid = Super (RequestBaseForm, Self) .validate ()
 26          IF  not ! Valid:
 27              # TODO doing here a return, code, msg, data error return ??? 
28              The raise JsonValidateErr ( " Field, IS The require? " )
 29  
30          return Self

Parsing the data according to the request header content-type, the Form wtfforms call parent class parameter analysis method __init__ after the administration of the properties of the parent class, wherein the custom method validate_for_api validate authentication method call parent class () by the parent to determine whether there is accurate

 

form form model:

1 # coding=utf-8
2 
3 from .JsonBaseValidate import RequestBaseForm
4 from wtforms import StringField,Form
5 from wtforms.validators import DataRequired,Length
6 
7 class Testform(RequestBaseForm):
8     username = StringField("username",validators=[DataRequired(),Length(min=2,max=20)])

A simple test, the routing code is as follows:

1 @user.route("/index",methods=["GET","POST"])
2 def xx():
3     req = Testform()
4     type = request.headers.get("Content-Type")
5     if req.validate_for_api():
6         return "requset username.data {} >> request context-type {}".format(req.username.data,type)
7     return "request validate failds..."

 

 

 

 This is json request, do not forget that in the header content-type of option to applocation / json

 

 

 

 

This is the form-data and form-urlencoded

 

 

 

Guess you like

Origin www.cnblogs.com/zengxm/p/12406499.html