django类视图与装饰和会话 [英] django class view with decorator and sessions
问题描述
我试图将一些我的django视图从基于函数的视图转换为基于类的视图,我遇到了一个小问题。
I'm trying to convert some of my django views over from function based views to class based views and I've run into a small problem.
我的OO是一种弱点,我想问题是我已经失去了哪里的事情进展。
My OO is kind of weak and I think the problem is that I've lost track of where things are going.
我有一个自定义登录装饰器,我需要在视图上我有...
I have a custom login decorator that I need on the views so I have...
首先我有一个View类从这个例子
http://www.djangosnippets.org/snippets/760/
First I have the View class from this example http://www.djangosnippets.org/snippets/760/
然后我的视图类看起来像这样...
Then my view class looks like this...
class TopSecretPage(View):
@custom_login
def __call__(self, request, **kwargs):
#bla bla view stuff...
pass
问题是,我的装饰不能访问request.session由于某种原因...
The problem is that my decorator can't access request.session for some reason...
我的装饰看起来像这样...
My decorator looks like this...
def myuser_login_required(f):
def wrap(request, *args, **kwargs):
# this check the session if userid key exist,
# if not it will redirect to login page
if 'field' not in request.session.keys():
return wrap
我认为这很简单,我错过了,感谢大家的耐心等待!
I think it's something simple that I'm missing so thanks for your patience everyone!
UPDATE:
好的,这里是我得到的错误...
UPDATE: Ok so here's the error that I get...
ViewDoesNotExist:在模块项目名称中试过TopSecretPage .application.views。错误是:类型对象'TopSecretPage'没有属性'会话'
"ViewDoesNotExist: Tried TopSecretPage in module projectname.application.views. Error was: type object 'TopSecretPage' has no attribute 'session'"
我简化装饰器,看起来像这样....
I simplified the decorator as well to look like this....
def myuser_login_required(request, *args, **kwargs):
# this check the session if userid key exist,
# if not it will redirect to login page
if 'username' not in request.session.keys():
return HttpResponseRedirect(reverse("login-page"))
return True
推荐答案
问题是你的包装器期望请求作为第一个参数,但类上的方法总是以self作为第一个参数。所以在你的装饰器中,它认为请求对象实际上是TopSecretPage本身。
The problem is that your wrapper expects "request" as the first argument, but a method on a class always takes "self" as the first argument. So in your decorator, what it thinks is the request object is actually TopSecretPage itself.
Vinay或artran的解决方案应该可以正常工作,所以我不再重复,只是想一个更清楚的描述可能会有帮助。
Either Vinay or artran's solutions should work, so I won't repeat them. Just thought a clearer description of the problem might be helpful.
这篇关于django类视图与装饰和会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!