【问题标题】:How to use GET without authentication but the POST/UPDATE with authentication in tastypie?如何在不进行身份验证的情况下使用 GET,但在美味派中使用身份验证的 POST/UPDATE?
【发布时间】:2015-12-18 20:05:31
【问题描述】:

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

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

我如何允许任何人在没有身份验证的情况下获得问题,但需要在一个资源类中通过帖子进行身份验证?

【问题讨论】:

    标签: django tastypie


    【解决方案1】:

    我如何允许任何人在没有身份验证的情况下获得问题,但需要在一个资源类中通过帖子进行身份验证?

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

    【讨论】:

      猜你喜欢
      • 2013-10-06
      • 2012-02-03
      • 2013-08-27
      • 2016-12-15
      • 2021-02-08
      • 2012-11-07
      • 2017-04-17
      • 2019-11-08
      • 1970-01-01
      相关资源
      最近更新 更多