flask_restful的reqparse校验参数

450 阅读3分钟
class Argument(object):
"""
:param name:名称或选项字符串列表,例如foo或 -f、 ——foo。
:param default:如果参数不在要求
:param dest:要添加到对象的属性的名称 返回者:meth:`~reqparse.RequestParser.parse_args()`。
:param bool required:参数是否可以省略(可选仅限)。
:param action:此参数时要执行的基本操作类型 在请求中遇到。有效选项为“存储”和“附加”。
:param ignore:是否忽略参数失败类型的情况转变
:param type:请求参数应为的类型转换。如果类型引发异常错误将在响应中返回。默认为:class:`unicode`在python2和python3中的:class:`str`。
:param location::class:`flask的属性。请求`object要从中获取参数(例如:标头、参数等),可以是迭代器。最后列出的项在结果集中优先。
:param choices:参数允许值的容器。
:param help:参数的简要描述,在参数无效时的响应。可选择包含一个“{error_msg}”内插令牌,将替换为类型转换器引发的错误的文本。
:param bool case_sensitive:请求中的参数值是否为是否区分大小写(这将将所有值转换为小写)
:param bool store_missing:参数默认值是否应如果请求中缺少参数,则存储。
:param bool trim:如果启用,则修剪参数周围的空白。
:param bool nullable:如果启用,则允许参数中为null值。
"""

    def __init__(self, name, default=None, dest=None, required=False, ignore=False, type=text_type, location=('json', 'values',), choices=(), action='store', help=None, operators=('=',), case_sensitive=True, store_missing=True, trim=False, nullable=True):
        self.name = name
        self.default = default
        self.dest = dest
        self.required = required
        self.ignore = ignore
        self.location = location
        self.type = type
        self.choices = choices
        self.action = action
        self.help = help
        self.case_sensitive = case_sensitive
        self.operators = operators
        self.store_missing = store_missing
        self.trim = trim
        self.nullable = nullable




# 具体使用
from flask_restful import Resource, reqparse
request_parser = reqparse.RequestParser()
request_parser.add_argument(name, default=None, dest=None, required=False,
                 ignore=False, type=text_type, location=('json', 'values',),
                 choices=(), action='store', help=None, operators=('=',),
                 case_sensitive=True, store_missing=True, trim=False,
                 nullable=True)


参数:
name
  – 参数名称。
default 
  – 请求没传入时,赋予默认值。
dest 
  – 重命名参数名称。当定义为name=name1, dest=name2时,接口请求传的名称是name1,上面例子args = parser.parse_args()语句获取的参数中,名字变为name2
required(bool)
  – 是否为必传参数。TrueFalse。
action
  – 在请求中遇到此参数时要采取的基本操作类型。有效选项是“store”和“append”。 action,其实是用来配置对该参数传多个值组成列表。默认是"store",配置为"append"的时候,穿多个值,最终会以列表的格式被接收。
ignore
  – 是否忽略类型转换错误
type 
  – 参数类型,python3为str,另外通过传int, float, FileStorage(文件)等实现多种请求参数。
location
  – 参数位置,要从(例如: location : args, form, json, headers, cookies等)中获取参数,可以是an迭代器,默认为(‘json’, ‘values’,)。
choice 
  – 参数允许值的容器。
help
  – 参数的简要说明,当参数无效时在响应中返回。可以选择包含“{error_msg}”插值标记,它将被类型转换器引发的错误文本替换。
case_sensitive(bool)
  – 请求中的参数值是否区分大小写(这会将所有值转换为小写)
store_missing(bool)
  – 如果请求中缺少参数,是否应存储参数默认值。
trim(bool)
  – 如果启用,则修剪参数周围的空格。
nullable(bool)
  – 如果启用,则在参数中允许空值。