Django:在基类中获取请求

时间:2016-01-24 23:53:55

标签: python django django-sessions

我有一个基类扩展对象,我正在尝试访问self.request.session,但它发出了一个错误,说请求不存在。

char arr[]=str.toCharArray

请帮忙

3 个答案:

答案 0 :(得分:0)

不,此时请求不存在  这个逻辑应该采用dispatch方法。

答案 1 :(得分:0)

class IndexView(TemplateView):
    template_name = "dashboard.html"

    def dispatch(self, request, *args, **kwargs):
        try:
            if self.request.session.get('sessionToken', None) == None:
                raise ValueError("User Not Logged In")
            register(APPLICATION_ID, REST_API_KEY, session_token=token)
            self.user = User.current_user()
            self.LoggedIn = True
            print("SUCCESS")
        except:
            print("FAILED")
            self.user = None
            self.LoggedIn = False
            print("CALLED INIT")
        return super(IndexView, self).dispatch(request, *args, **kwargs)

答案 2 :(得分:0)

我最终在基类的init中通过kwargs传递sessionToken,并做了我打算做的任何事情。

class BaseTemplateView(object):

    def __init__(self,  *args, **kwargs):


        try:

            if 'sessionToken' in kwargs:
                token = kwargs['sessionToken']
            else: 
                raise ValueError('Missing Token')

            register(APPLICATION_ID, REST_API_KEY, session_token=token)
            self.user = User.current_user()
            self.LoggedIn = True
            print("SUCCESS")
        except:
            print("FAILED")
            self.user = None
            self.LoggedIn = False
        print("CALLED INIT")

class IndexView(BaseTemplateView, TemplateView):
    template_name = "dashboard.html"

    def dispatch(self, request, *args, **kwargs):
        token = self.request.session.get('sessionToken', None)
        if  token != None:
            print("Token : {0}".format(token))
            super(IndexView, self).__init__( *args, sessionToken=token)

        if not self.isLoggedIn:
            HttpResponseRedirect('/')

        return super(IndexView, self).dispatch(request, *args, **kwargs)

希望这能帮助任何像我这样的django新手,而不是花一天时间试图找出一个非常简单的解决方案