Tastypie:用于GET的身份验证和用于POST的匿名身份验证

Tho*_*s K 10 python api django rest tastypie

我使用Django/Tastypie来管理我的用户集合.

是否可以允许匿名用户在API中进行POST(在某个端点创建新用户时)并限制经过身份验证的用户仅限他们自己的用户,但不是所有用户?

谢谢你的帮助.

小智 19

我发现最简单的事情是继承我正在使用的Authentication类.只需覆盖方法POST时is_authenticated返回True的方法.

class AnonymousPostAuthentication(BasicAuthentication):
    """ No auth on post / for user creation """

    def is_authenticated(self, request, **kwargs):
        """ If POST, don't check auth, otherwise fall back to parent """

        if request.method == "POST":
            return True
        else:
            return super(AnonymousPostAuthentication, self).is_authenticated(request, **kwargs)
Run Code Online (Sandbox Code Playgroud)

我把我的验证放在了子类Validation和覆盖中is_valid.

我按照Sampson上面所做的那样进行GET过滤.