如何为我的 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
问题是..我不知道在这种情况下如何编写正确的装饰器!论据是什么?有哪些功能?如何?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
仅使用
@check_login
而不是check_login()
- 否则你的装饰器必须在你执行home = check_login()(home)
这是一个装饰器示例:
如果用户名字段设置为“blah”,则该装饰器将调用执行您的登录函数,然后调用原始方法。
Use only
@check_login
instead ofcheck_login()
- otherwise your decorator has to return a decorate as you are doinghome = check_login()(home)
Here's an example decorator:
This decorator will call execute your login function if the username field is set to "blah" and then call the original method.
普通装饰器只是一个函数,它接受一个函数或类并返回其他内容(通常是相同的类型,但这不是必需的)。参数化装饰器是返回装饰器的函数。
因此,考虑到这一点,我们创建一个闭包并返回它:
A plain decorator is simply a function that takes a function or class and returns something else (usually the same type, but this is not required). A parametrized decorator is a function that returns a decorator.
So, with that in mind we create a closure and return it:
这是我编写的一个装饰器,用于检查用户是否属于某个组。它显示了更多一点。
https://github.com/mzupan/django-decorators/blob/master /auth.py
你可以像用户可以在 group1 或 group2 中一样使用它
,如果他们不是,他们会得到 404 页面
Here is a decorator I wrote to check if the user is in a certain group. It shows a bit more.
https://github.com/mzupan/django-decorators/blob/master/auth.py
You use it like
The user can be in either group1 or group2 if they are not they get a 404 page