简体   繁体   English

我如何获得装饰师的退货?

[英]How can I access a return from a decorator?

I have an auth decorator, that I am using to verify tokens for logins.我有一个身份验证装饰器,用于验证登录令牌。 I would like to return the UID from the decorator but I am unsure of how to do that?我想从装饰器返回 UID,但我不确定该怎么做? Any advice?有什么建议吗? (The idea is that we can use that UID from the token to access user-specific resources on our server) (想法是我们可以使用令牌中的 UID 来访问我们服务器上的用户特定资源)

Decorator:装饰器:

def check_auth(id_token):
    decoded_token = auth.verify_id_token(id_token)
    uid = decoded_token['uid']
    print(uid)
    return uid


def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.headers.get("Authorization")
        if not auth or not check_auth(auth):
            message = {"error": "Authorization Required"}
            resp = message
            return resp
        return f(*args, **kwargs)

    return decorated

The return value of a decorator is what will replace the decorated function.装饰器的返回值将替换已装饰的 function。 If you return a UID from the decorator your decorated function will be replaced by the UID.如果你从装饰器返回一个 UID,你装饰的 function 将被 UID 替换。

What you can do is to inject the UID into the function call:您可以做的是将 UID 注入到 function 调用中:

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.headers.get("Authorization")
        if not auth or not check_auth(auth):
            message = {"error": "Authorization Required"}
            resp = message
            return resp
        kwargs['uid'] = check_auth(auth)
        return f(*args, **kwargs)

    return decorated

This requires all decorated functions to accept a uid argument:这要求所有修饰函数接受一个uid参数:

@requires_auth
def decorated_function(uid):
    …

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

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