Flask-Restful parameter validation

parameter validation

The Flask-Restful plugin provides a package similar to WTForms to verify whether the submitted data is legal, called reqparse. The following is the basic usage:

'''
parser = reqparse.RequestParser()
parser.add_argument('username', type=str, help='Please enter username')
args = parser.parse_args()

‘’’

add_argument can specify the name of this field, the data type of this field, etc. The following will explain some parameters of this method in detail:

1. 

default : The default value, if this parameter has no value, then the value specified by this parameter will be used.
2.
required: Whether it is required. The default is False, if set to True, then this parameter must be submitted.
3.
type : The data type of this parameter. If specified, the specified book type will be used to convert the submitted value.
4.
choices : option, the submitted value can only pass the verification if it satisfies the value in this option, otherwise the verification will fail.
5.
help : error message. If the validation fails, the value specified by this parameter will be used as the error message.
6.
trim : Whether to remove leading and trailing spaces.

For the type attribute, you can use some data types that come with python, or you can use some specific data types under flask_restful.inputs to force conversion. For example, some commonly used ones:

1. 
url : 会判断这个参数的值是否是一个url,如果不是,那么久会抛出异常。
2. 

regex : regular expression.
3.
date : Convert this string to datetime.date data type. If the conversion is unsuccessful, an exception is thrown.

Guess you like

Origin blog.csdn.net/chenxuezhong0413/article/details/114275578