如何为Django / Python视图编写装饰器?


问题内容

这是我的看法。基本上,它会根据是否登录返回不同的响应。

@check_login()
def home(request):
    if is_logged_in(request): 
        return x
    else:
        return y

这是我的装饰代码。我只想检查请求中是否包含标题,如果有,请登录。

#decorator to log the user in if there are headers
def check_login():
    def check_dec(func):
        if request.META['username'] == "blah":
            login(request, user)

    return check_dec

问题是..在这种情况下,我不知道如何编写适当的装饰器!!!有什么争论?有什么功能?怎么样?


问题答案:

仅使用@check_login代替check_login()-否则您的装饰器必须在执行操作时返回装饰home = check_login()(home)

这是一个示例装饰器:

def check_login(method):
    @functools.wraps(method)
    def wrapper(request, *args, **kwargs):
        if request.META['username'] == "blah"
            login(request, user) # where does user come from?!
        return method(request, *args, **kwargs)
    return wrapper

如果用户名字段设置为“ blah”,则此修饰器将调用执行您的登录功能,然后调用原始方法。