有你需要考虑两件事情。认证和授权。
首先,如果请求方法是GET,则无论API密钥如何,都需要对所有用户进行身份验证,对于所有其他方法,使用ApiKeyAuthentication。
现在,所有经过身份验证的用户都需要授权。在这里您还需要确保始终允许GET请求。像这样的东西应该让你开始:
from tastypie.resources import ModelResource
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import DjangoAuthorization
class MyAuthentication(ApiKeyAuthentication):
"""
Authenticates everyone if the request is GET otherwise performs
ApiKeyAuthentication.
"""
def is_authenticated(self, request, **kwargs):
if request.method == 'GET':
return True
return super(MyAuthentication, self).is_authenticated(request, **kwargs)
class MyAuthorization(DjangoAuthorization)
"""
Authorizes every authenticated user to perform GET, for all others
performs DjangoAuthorization.
"""
def is_authorized(self, request, object=None):
if request.method == 'GET':
return True
else:
return super(MyAuthorization, self).is_authorized(request, object)
class MyResource(ModelResource):
class Meta:
authentication = MyAuthentication()
authorization = MyAuthorization()
所以基本上你使用ApiKeyAuthentication
和DjangoAuthorization
方法只缺GET请求特殊处理。
来源
2012-09-05 01:33:24
kgr
感谢您的详细解决方案。它运作良好。我跳过了MyAuthorization,因为DjangoAuthorization已经允许所有的GET请求。 –
不客气:)我很高兴它的工作。 – kgr