所以我刚开始将旧代码移植到基于类的视图,我仍然是新手。我的问题与Django mixins有关,我有一个mixin,我将在各种类中使用它来验证一些信息。问题是我不知道如何访问它返回的信息而不会得到500内部错误。
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访问数据,我该怎么做正确的方法?
答案 0 :(得分:4)
self.get_valid_token()
是正确的。但是,您在该方法中有几个错误,这无疑是导致问题的原因:特别是,您可以在不定义任何时候引用request
。我希望你的意思是self.request
。