您需要考虑两件事。身份验证和授权。
首先,如果请求方法是 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 请求的特殊处理。