如何在没有身份验证的情况下使用GET,但在tastypie中使用POST / UPDATE进行身份验证?

时间:2015-12-18 20:05:31

标签: django tastypie

假设我在tastypie中有一个资源:

class QuestionResource(ModelResource):
    class Meta:
        queryset = Question.objects.all()
        allowed_methods = ['get', 'post']
        authentication = BasicAuthentication()

如何在没有身份验证的情况下允许任何人获取问题,但需要在一个资源类中使用post进行身份验证?

1 个答案:

答案 0 :(得分:0)

  

如何在没有身份验证的情况下允许任何人获取问题,但需要在一个资源类中使用post进行身份验证?

一个好方法是实现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,但它是一个特定资源的特定实现。如果您的应用程序有多个需要相同身份验证语义的资源,请使用子类化使其可重用。

相关问题