猿问

Tastypie自动登出

我正在使用Tastypie创建基于Django 1.4.3的API。我使用ApiKey对用户进行身份验证。默认情况下,ApiKey不能过期。但是created在apikey表中有带有datetime的列。即使我将其更改为2010年份,密钥也仍然有效。

我的问题是,如何created以最简单的方式使该列有用,并禁止访问比说的24小时更早的键,这样做有意义吗?

目前,我还不知道该如何实现。

我不希望有现成的解决方案。一些有用的提示。


一只甜甜圈
浏览 132回答 2
2回答

茅侃侃

我get_key在ApiKeyAuthentication中通过覆盖方法找到了解决方案。class MyApiKeyAuthentication(ApiKeyAuthentication):&nbsp; &nbsp; def get_key(self, user, api_key):&nbsp; &nbsp; &nbsp; &nbsp; """&nbsp; &nbsp; &nbsp; &nbsp; Attempts to find the API key for the user. Uses ``ApiKey`` by default&nbsp; &nbsp; &nbsp; &nbsp; but can be overridden.&nbsp; &nbsp; &nbsp; &nbsp; """&nbsp; &nbsp; &nbsp; &nbsp; from tastypie.models import ApiKey&nbsp; &nbsp; &nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; api_key = ApiKey.objects.get(user=user, key=api_key)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; current_time = datetime.utcnow()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; current_time = current_time.replace(tzinfo=pytz.utc)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; week = timedelta(7)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if not (current_time - api_key.created) < week:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; api_key.delete()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return self._unauthorized()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; api_key.created = current_time&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; api_key.save()&nbsp; &nbsp; &nbsp; &nbsp; except ApiKey.DoesNotExist:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return self._unauthorized()&nbsp; &nbsp; &nbsp; &nbsp; return True
随时随地看视频慕课网APP

相关分类

Python
我要回答