首页 > 其他分享 >Flask 学习-34.restful-full 请求参数自定义参数校验类型 (reqparse.RequestParser() )

Flask 学习-34.restful-full 请求参数自定义参数校验类型 (reqparse.RequestParser() )

时间:2022-09-01 22:27:28浏览次数:58  
标签:full 自定义 self required parser argument 参数 password type

前言

在校验请求参数的时候,除了一些基本的required=True, type类型外,还会遇到一些校验,比如是否为空,字符串长度,以及一些自定义的参数规则。

add_argument 参数

下面是add_argument 可以使用的参数,部分源码如下:

class Argument(object):

    """
    :param name: Either a name or a list of option strings, e.g. foo or
        -f, --foo.
    :param default: The value produced if the argument is absent from the
        request.
    :param dest: The name of the attribute to be added to the object
        returned by :meth:`~reqparse.RequestParser.parse_args()`.
    :param bool required: Whether or not the argument may be omitted (optionals
        only).
    :param action: The basic type of action to be taken when this argument
        is encountered in the request. Valid options are "store" and "append".
    :param ignore: Whether to ignore cases where the argument fails type
        conversion
    :param type: The type to which the request argument should be
        converted. If a type raises an exception, the message in the
        error will be returned in the response. Defaults to :class:`unicode`
        in python2 and :class:`str` in python3.
    :param location: The attributes of the :class:`flask.Request` object
        to source the arguments from (ex: headers, args, etc.), can be an
        iterator. The last item listed takes precedence in the result set.
    :param choices: A container of the allowable values for the argument.
    :param help: A brief description of the argument, returned in the
        response when the argument is invalid. May optionally contain
        an "{error_msg}" interpolation token, which will be replaced with
        the text of the error raised by the type converter.
    :param bool case_sensitive: Whether argument values in the request are
        case sensitive or not (this will convert all values to lowercase)
    :param bool store_missing: Whether the arguments default value should
        be stored if the argument is missing from the request.
    :param bool trim: If enabled, trims whitespace around the argument.
    :param bool nullable: If enabled, allows null value in argument.
    """

    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

nullable=False 不允许为None

required=True 设置该参数是必传项, nullable=False 是设置该参数不允许为None

class Register(Resource):

    def post(self):
        # 校验入参
        parser = reqparse.RequestParser()
        parser.add_argument('username', required=True, type=str,  nullable=False, help='username is required')
        parser.add_argument('password', required=True, type=str,  nullable=False, help='password is required')
        args = parser.parse_args()

        # # 获取入参
        # data = request.get_json()
        print(f'请求入参:{args}')
        return jsonify({
            "code": 0,
            "msg": "success"
        })


# 注册
api.add_resource(Register, '/api/v1/register')

需注意的是这里是不能为null, 传空字符串还是可以的。

default=''设置默认值

对address 参数设置默认值,当用户没传address 参数的时候,就会取默认值

    def post(self):
        # 校验入参
        parser = reqparse.RequestParser()
        parser.add_argument('username', required=True, type=str,  nullable=False, help='username is required')
        parser.add_argument('password', required=True, type=str,  nullable=False, help='password is required')
        parser.add_argument('address', default='上海市',  type=str, help='address invalid')
        args = parser.parse_args()
        print(f'请求入参:{args}')

请求示例

POST http://127.0.0.1:5000/api/v1/register HTTP/1.1
User-Agent: Fiddler
Host: 127.0.0.1:5000
Content-Type: application/json
Content-Length: 56

{
    "username": "test",
    "password" : "111111"
}

args 得到的参数

{'username': 'test', 'password': '111111', 'address': '上海市'}

choices 设置参数可选值

比如性别设置可选项:男、女

    def post(self):
        # 校验入参
        parser = reqparse.RequestParser()
        parser.add_argument('username', required=True, type=str,  nullable=False, help='username is required')
        parser.add_argument('password', required=True, type=str,  nullable=False, help='password is required')
        parser.add_argument('sex', choices=["男", "女"],  type=str, help='sex invalid')
        args = parser.parse_args()

        print(f'请求入参:{args}')

请求示例,sex不是可选项的时候会报400

POST http://127.0.0.1:5000/api/v1/register HTTP/1.1
User-Agent: Fiddler
Host: 127.0.0.1:5000
Content-Type: application/json
Content-Length: 73

{
    "username": "test",
    "password" : "111111",
    "sex": "x"
}

HTTP/1.1 400 BAD REQUEST
Server: Werkzeug/2.2.2 Python/3.8.5
Date: Thu, 01 Sep 2022 13:40:14 GMT
Content-Type: application/json
Content-Length: 57
Connection: close

{
    "message": {
        "sex": "sex invalid"
    }
}

设置字符串长度

比如限制 password 是 6-16 位,由于 add_argument 没提供对应的方法,需我们自定义参数校验类型

class Register(Resource):

    @staticmethod
    def password_validate(value, name):
        if len(value) < 6 or len(value) > 16:
            raise ValueError(name + '参数长度不合法')
        return value

    def post(self):
        # 校验入参
        parser = reqparse.RequestParser()
        parser.add_argument('username', required=True, type=str,  nullable=False, help='username invalid')
        parser.add_argument('password', required=True, type=self.password_validate,  
                            nullable=False, help='password invalid must 6-16')
        # parser.add_argument('sex', choices=["男", "女"],  type=str, help='sex invalid')
        args = parser.parse_args()

        print(f'请求入参:{args}')

如果密码长度小于6位,会返回400

POST http://127.0.0.1:5000/api/v1/register HTTP/1.1
User-Agent: Fiddler
Host: 127.0.0.1:5000
Content-Type: application/json
Content-Length: 55

{
    "username": "test",
    "password" : "12345"
}

HTTP/1.1 400 BAD REQUEST
Server: Werkzeug/2.2.2 Python/3.8.5
Date: Thu, 01 Sep 2022 14:04:30 GMT
Content-Type: application/json
Content-Length: 76
Connection: close

{
    "message": {
        "password": "password invalid must 6-16"
    }
}

标签:full,自定义,self,required,parser,argument,参数,password,type
From: https://www.cnblogs.com/yoyoketang/p/16647988.html

相关文章

  • Flask 学习-33.restful-full 请求参数校验reqparse.RequestParser()
    前言接口请求参数的校验是个大的工作量,参数比较少的时候还可以一个个去判断,参数多了写起来就很麻烦了。reqparse解析请求参数尽管Flask能够简单地访问请求数据(比如......
  • Windows下Conda自定义env安装目录
    楔子windows下,conda会将新的环境安装到%USERFROFILE%/.cond/envs下,但是到后来清理C盘的时候,就想着如何将这个envs搬到D盘我将envs移动到D盘后,然后将C盘的envs删除了,然......
  • [ROS学习] 12.参数的使用与编程方法
    笔记参考:【ROS学习笔记】12.参数的使用与编程方法内容参考:基于B站ROS公开课:【古月居】古月·ROS入门21讲更多详情:http://wiki.ros.org/Parameter%20Server本节说明至......
  • 【Azure Redis 缓存】Azure Redis 功能性讨论三: 调优参数配置
    问题描述在使用AzureRedis的服务中,遇见了以下系列问题需要澄清:在开源Redis6.0中,多线程默认禁用,只使用主线程。如需开启需要修改redis.config配置文件。Redis的多线......
  • D365: Business event(二)自定义功能事件
    D365F&O中自定义功能事件Demo(销售订单行更新剩余交货量)1,创建Contract类,继承BusinessEventsContract 2,创建Event类,继承BusinessEventsBase 3,在触发点注册事件......
  • pytest系列——pluggy插件源码解读(三)add_hookspecs增加自定义的接口类
    pluggy使用举例子代码:下面这个例子中前面已经分析完了,下面的步骤就是pm.add_hookspecs(MySpec)这个一步骤了,同样,这个add_hookspecs方法也是PluginManager类的一个方法,下......
  • 21 forms组件-参数initial&instance应用
    简单来讲:如果你想传入前端的页面中附带值,那么在实例化forms中:form=SecondModelForm(data=request.POST,instance=permission_obj)returnrender(request,'rbac/chan......
  • BI如何实现用户身份集成自定义安全程序开发
    统一身份认证是整个IT架构的最基本的组成部分,而账号则是实现统一身份认证的基础。做好账号的规划和设计直接决定着企业整个信息系统建设的便利与难易程度,决定着系统能否......
  • Flask 学习-32.flask_jwt_extended 自定义装饰器
    前言创建自己的装饰器来扩展此扩展提供的装饰器的功能。例如,您可能想要创建自己的装饰器来验证JWT是否存在以及验证当前用户是否是管理员。自定义装饰器flask_jwt_ext......
  • 屏幕深度 自定义深度 纹理元素
      SceneTexture节点,可以帮助我们获取很多信息,例如像素深度,法线,自定义深度,后处理输入,粗糙度,金属值等借助SceneTexture节点中的SceneDepth,我们获取到了渲染像素在屏幕......