Django RESTful Framework如何从HTTP标头中获取令牌的用户模型?

时间:2017-08-23 13:06:02

标签: django http-headers django-rest-framework

我正在构建我的Django RESTful Framework来检索和发布Mobile的数据。我正在使用Django-rest-auth(这只是具有RESTful功能的all-auth;更多信息:http://django-rest-auth.readthedocs.io/en/latest/)。

当移动设备在HTTP标头中发送用户令牌时,Django RESTful Framework(或Django)如何找到用户的模型?

例如:

HTTP METHOD: POST
headers : Authorization eyl3of9iskjfpjowpefjsopeff (This is token and random string) 
body : {
    post_title: "This is my first post"
    post_content: "This is the content" 
}

这是我的设置:

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.AllowAny',
        # 'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        # 'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
}

这是我想要找到用户模型的地方:

class CreatePost(generics.CreateAPIView):
    def get_queryset(self, **kwargs):
        owner = User.objects.filter(user= ##) # right here!
        post_title =
        post_content = 

或建议采用其他方法?

1 个答案:

答案 0 :(得分:2)

通常,您的Token只是一个 Django模型,它存储在您的数据库中。

它与OneToOne模型有User关系,而这只是它们的相关关系(在rest_framework.authtoken中)。您可以在DRF source中看到它。

直接考试:

from rest_framework import generics
from rest_framework import status
from rest_framework.authtoken.models import Token
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# You can directly import your Token model for usage

from .serializers import UserLoginSerializer


class UserLogin(generics.CreateAPIView):
    serializer_class = UserLoginSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)

        user = serializer.validated_data['user']
        token, _ = Token.objects.get_or_create(user=user)
        # Here you either get a Token if it exists in your db
        # Or generate it if it is not created yet

        # See that you directly get the token with your user:
        # Token.objects.get_or_create(user=user)

        # You can also access it vice-versa: token.user <-> user.token
        # Because it is a OneToOne relation

        response_data = {
            'id': user.id,
            'token': token.key
        }

        headers = self.get_success_headers(serializer.data)

        return Response(response_data, status=status.HTTP_200_OK, headers=headers)

注意:如果您使用的是JWT,请查看how a token is linked with the user

在你的情况下:

class CreatePost(generics.CreateAPIView):
    def get_queryset(self, **kwargs):
        owner = self.request.user
        # Are you sure you don't want to get the current request user?
        # Why you should filter with token?

        post_title = ...
        post_content = ...

您的身份验证类(在您的情况下为JSONWebTokenAuthentication,它会自动将request.user设置为正确的,您可以在视图中访问它。)