美文网首页
装饰器-验证API入参

装饰器-验证API入参

作者: 木叶苍蓝 | 来源:发表于2020-01-09 15:28 被阅读0次

    这里主要验证GET请求和POST请求

    GET传参

    GET把参数包含在URL中


    get.png
    POST传参

    POST参数放到body中

    post.png
    进入主题wraps.py
    #!/usr/bin/python
    #-*- coding:UTF-8 -*-
    
    import time
    from flask import request
    from functools import wraps
    
    def request_data():
        if request.method in ("POST", "PUT"):
            return request.get_json(force=True)
        else:
            return request.value
    
    def validate_params(required):
        '''
        check the input params
        :param required:
            type(list or tuple)
            item:
                :type(list or tuple)
                length should be >= 2
                item[0]: key name
                item[1]: key type
                item[2]: scope of key's value(not must)
            example:
                required = [(‘fence_name’, unicode), ('trigger_time', int), ('trigger_type', int, range(3)), ('action', int, (1,2))]
            :return
        '''
        def _validate_params(f):
            @wraps(f)
            def wrapper(*args, **kwargs):
                if not isinstance(required, (list, tuple)):
                    raise TypeError, "The params required must be list!"
                for req in required:
                    if len(req) < 2:
                        # Check the key is Exist:
                        try:
                            client_val = request_data()[req[0]]   
                        except:
                            return "Key = {} required param error".format(req[0]) 
                        client_val_type = req[1]
                        # Check the key's type:
                        if not isinstance(client_val, client_valu_type):
                            try:
                                client_val = client_val_type(client_val)
                            except ValueError, e:
                                    return "Key = {} type error!".format(req[0])
                    if len(req) >= 3:
                        if client_val not in req[2]:
                            return "Key = {} value = {} error!".format(req[0], client_val)
                val = f(*args, **kwargs)
                return val
            return wrapper
        return _validate_params
    

    写一个超级简单的web程序my_appp.py

    #!/usr/bin/python
    #-*- coding:UTF-8 -*-
    
    from flask import Flask
    
    from wrap import request_data
    from wrap import validate_params
    
    app = Flask(__name__)
    
    @app.route('/', methods=['GET'])
    @validate_params(required=[('name', unicode), ('age', int, range(1, 100)), ('sex', int, [1, 2])])
    def get():
        name = unicode(request_data().get("name"))
        age = int(request_data().get("age"))
        sex = int(request_data().get("sex"))
        return "name = %s, age = %s, sex = %s"%(name, age, sex)
    
    @app.route('/', methods=['POST'])
    @validate_params(required=[('name', unicode), ('age', int, range(1, 100)), ('sex', int, [1, 2])])
    def post():
        name = unicode(request_data().get("name"))
        age = int(request_data().get("age"))
        sex = int(request_data().get("sex"))
        return "name = %s, age = %s, sex = %s"%(name, age, sex)
      
    if __name__ == "__main__":
          app.run(host='0.0.0.0', port=5000, debug=True)
    

    参数说明:

    @validate_params(required=[('name', unicode), ('age', int, range(1, 100)), ('sex', int, [1, 2])])
    

    @: python 语法糖
    validate_params: 装饰器
    required: 关键字参数,类型必须是list或者tuple
    ('name', unicode): 需要验证的变量名,类型必须是 unicode
    ('age', int, range(1, 100)): 需要验证的变量名,类型必须是int,并且1 <= age < 100
    ('sex', int, [1, 2]): 需要验证的变量名,类型必须是int,只能是 1 或者 2

    相关文章

      网友评论

          本文标题:装饰器-验证API入参

          本文链接:https://www.haomeiwen.com/subject/uraractx.html