Django自定义身份验证

时间:2016-03-03 12:23:29

标签: python django django-rest-framework

我在我的应用程序中使用Django REST Framework。我需要身份验证,但不是默认身份验证。我有一个模特:

class Worker(models.Model):
    token = models.CharField(...)
    ip = models.GenericIPAddressField(...)
    created_date = models.DateTimeField(...)
    last_update = models.DateTimeField(...)

Worker通过我的API发送消息,以查看继承自Django REST Framework的APIView的WorkerView。令牌在请求的标题中发送:

class WorkerView(APIView):
    def post(self, request):
        # some not important code

我有一个验证方法:

def authenticate(request):
    try:
        ip = request.META.get("REMOTE_ADDR", None)
        token = request.META.get("HTTP_AUTHORIZATION", None)
    ...

我想到了两个解决方案:

  1. 创建一个mixin类并在我的WorkerView中继承它:

    class WorkerView(AuthenticationMixin, APIView)
        ...
    
  2. 从我的authenticate方法创建一个类装饰器并像这样使用它:

    @authenticate
    class WorkerView(APIView)
    
  3. 但是在这两种情况下我都需要将请求参数传递给authenticate方法。 怎么做?或者可能有更好的解决方案来解决我的问题?

1 个答案:

答案 0 :(得分:0)

为什么不创建此处定义的自定义身份验证类? http://www.django-rest-framework.org/api-guide/authentication/#custom-authentication