简体   繁体   English

Flask:装饰器测试查询字符串 arguments

[英]Flask : Decorator to test query string arguments

I begin with Flask and try to create the best code possible.我从 Flask 开始并尝试创建最好的代码。 For some simple route, I would like to check if some required arguments are present.对于一些简单的路线,我想检查是否存在一些必需的 arguments。 At this time, I create this decorator这个时候我创建这个装饰器

def validate_qs_arguments(arguments):
    def decorator(fn):
        def wrapped_function(*args, **kwargs):
            for argument_name in arguments:
                if request.args.get(argument_name) is None:
                    abort(400, "'{name}' argument is missing".format(name=argument_name))
            return fn(*args, **kwargs)
        return update_wrapper(wrapped_function, fn)
    return decorator

I can use it like this:我可以这样使用它:

@validate_qs_arguments(arguments=["pid", "datastream"])

It works fine.它工作正常。 But I'm trouble than Flask doesn't provide a build-in function/decorator to do the same thing.但我很麻烦 Flask 没有提供内置函数/装饰器来做同样的事情。 Is it exists a better to do that?这样做有更好的方法吗? A build-in flask decorator/function?内置 flask 装饰器/功能?

Thanks for your help.谢谢你的帮助。

Flask doesn't provide a build-in... Flask is a micro-framework that was built around a plug-in approach. Flask 不提供内置... Flask 是一个围绕插件方法构建的微框架。 If you want more out of it, use extensions (Flask-restful is one of it as it was said in comments), or python marshmallow , or other lib, or write your own implementation.如果你想要更多,使用扩展(Flask-restful 是其中之一,正如评论中所说),或python marshmallow或其他库,或编写你自己的实现。

Decorator func:装饰函数:

def check_form_key(key_list:list):
    def real_decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            if request.form is None:
                return Result(False, Error("FR"))
            not_exist_key = []
            for key in key_list:
                if key in request.form:
                    continue
                else:
                    not_exist_key.append(key)

            if len(not_exist_key) > 0:
                return Result(False,"this keys not exist {0}".format(not_exist_key))
            return func(*args, **kwargs)
        return wrapper
    return real_decorator

Usage:用法:

@check_form_key([“name”,”code”])
def check():
   pass
def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if "log" in session:
             return f(*args, **kwargs)
        else:
             return redirect(url_for("login"))
    return decorated_function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM