这是我的看法。基本上,它根据是否登录返回不同的响应。
@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”,此装饰器将调用执行您的登录函数,然后调用原始方法。
关于python - 如何为我的 Django/Python View 编写装饰器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4320703/