2013-02-18 85 views
4

所以我剛開始將我的舊代碼移植到基於類的視圖,並且我仍然是新的。我的問題與Django mixin有關,在這裏我有一個mixin,我將在各個類中使用它來驗證一些信息。問題是,我不知道如何訪問它返回的信息,而沒有得到500內部錯誤。正確使用Django Mixins

class CheckTokenMixin(object): 
    def request_token(self,request): 
     params = {'username':settings.OAUTH_USERNAME,'password':hashlib.sha256(settings.OAUTH_PASSWORD).hexdigest()} 
     req = Request(settings.REMOTE_SERVER+'oauth', urllib.urlencode(params)) 
     return json.loads(urlopen(req).read()) 

    def get_valid_token(self): 
     if datetime.datetime.now() > request.session['access_token'].creation_date + datetime.timedelta(days=1): 
      temp = self.request_token(request) 
      tokenobj = AccessToken.objects.all()[:1].get() 
      tokenobj.access_token = temp['token'] 
      tokenobj.creation_date = datetime.datetime.now() 
      tokenobj.save() 
      request.session['access_token'] = tokenobj 

     return request.session['access_token'] 

    def get_context_data(self, **kwargs): 
     ctx = super(CheckTokenMixin, self).get_context_data(**kwargs) 
     ctx['access_token'] = self.get_valid_token() 
     return ctx 

class RateAppView(LoginRequiredMixin, JSONResponseMixin, AjaxResponseMixin, CheckTokenMixin, View): 

    @method_decorator(csrf_protect) 
    def dispatch(self, *args, **kwargs): 
     return super(RateAppView, self).dispatch(*args, **kwargs) 

    def post_ajax(self, request, username): 
     u = get_object_or_404(User, pk=current_user_id(request)) 
     city_obj = City.objects.get(id=request.POST.get('city_id', None)) 
     x = self.get_valid_token 
     print "teste: " , x.access_token 
     print "teste2: " , self.get_context_data.['access_token'].access_token 

我想是這樣

self.get_valid_token

self.get_context_data。[ 'ACCESS_TOKEN']。ACCESS_TOKEN

來訪問我的mixin中的數據,我該如何正確使用它?

回答

4

self.get_valid_token()會是正確的。但是,您在該方法中有幾個錯誤,這無疑是造成問題的原因:特別是,您可以參考request而不必在任何時候對其進行定義。我希望你的意思是代替self.request

+0

感謝是的;) – psychok7 2013-02-18 12:14:11