简体   繁体   English

PyMongo装饰变量到函数的上下文

[英]PyMongo decorator variable to context of function

How can I pass a value into the context of a function from this decorator? 如何从此装饰器将值传递到函数的上下文中? Lets say authStr as an example. 让我们以authStr为例。

# decorator for endpoints that need auth token
def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        authStr = request.headers.get('Authorization') # 'Bearer thisisatokenstrhere'
        check_auth(authStr) # check if expired
        if not check_auth(authStr):
            return abort(401)
        return f(*args, **kwargs)
    return decorated

You have the kwargs dict, you can simply add it there: 您拥有kwargs字典,只需在此处添加即可:

kwargs['authStr'] = authStr
return f(*args, **kwargs)

Although I don't know how useful that will be, unless the decorated function is already expecting that kwarg. 尽管我不知道它会有多大用处,除非装饰的功能已经在期待它了。

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

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