我如何允许任何人在没有身份验证的情况下获得问题,但需要在一个资源类中通过帖子进行身份验证?
一个好的方法是实现 BasicAuthentication 的子类:
class CustomAuthentication(BasicAuthentication):
def is_authenticated(self, request, **kwargs):
if request.method == 'GET':
return True
return BasicAuthentication.is_authenticated(request, **kwargs)
然后使用您的新类作为authentication 选项:
class QuestionResource(ModelResource):
class Meta:
queryset = Question.objects.all()
allowed_methods = ['get', 'post']
authentication = CustomAuthentication()
更多信息可以在tastypie documentation 中找到。
另一种方法是覆盖资源中的 is_authenticated 方法(默认情况下调用 Meta 中的 Authentication 实例):
class QuestionResource(ModelResource):
(...)
def is_authenticated(self, request):
if request.method == 'GET':
return True
return ModelResource.is_authenticated(request)
请注意,虽然这种方法是viable and documented,但它是针对特定资源的特定实现。如果您的应用程序有多个需要相同身份验证语义的资源,请使用子类化使其可重用。