如何为Django / Python视图编写装饰器? [英] How do I write a decorator for my Django/Python view?

查看:182
本文介绍了如何为Django / Python视图编写装饰器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  @check_login()
def home请求):
如果is_logged_in(请求):
返回x
其他:
返回y

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

  #decorator将用户登录如果有标题
def check_login():
def check_dec(func):
if request.META ['username'] ==blah:
login(request,用户)

返回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,用户)#用户来自哪里?
return method(request,* args,** kwargs)
return wrapper

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


Here's my view. Basically, it returns different Responses based on whether it's logged in or not.

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

Here's my decorator code. I just want to check if the request has headers, and if so, log him in.

#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

The problem is..I don't know how to write a proper decorator in this case!!! What are the arguments? What are the functions? How?

解决方案

Use only @check_login instead of check_login() - otherwise your decorator has to return a decorate as you are doing home = check_login()(home)

Here's an example decorator:

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

This decorator will call execute your login function if the username field is set to "blah" and then call the original method.

这篇关于如何为Django / Python视图编写装饰器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆