gpt4 book ai didi

python - 覆盖 Django Rest 中的 authToken View

转载 作者:太空狗 更新时间:2023-10-30 02:58:01 26 4
gpt4 key购买 nike

我在 Django 中使用基于 token 的身份验证,除了要返回的 token 外,还需要添加用户对象。

如何覆盖此类 View ?我需要在哪里添加此类并进行更改?目前这是在 rest_framework 包中找到的,我不想修改库。

from rest_framework import parsers, renderers
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.serializers import AuthTokenSerializer
from rest_framework.response import Response
from rest_framework.views import APIView


class ObtainAuthToken(APIView):
throttle_classes = ()
permission_classes = ()
parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)
renderer_classes = (renderers.JSONRenderer,)
serializer_class = AuthTokenSerializer
print "dasdsa"

def post(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
return Response({'token': token.key})


obtain_auth_token = ObtainAuthToken.as_view()

最佳答案

来自 docs .

首先,您需要扩展 ObtainAuthToken 类。

# views.py

from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.response import Response

class CustomAuthToken(ObtainAuthToken):

def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data,
context={'request': request})
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
return Response({
'token': token.key,
'user_id': user.pk,
'email': user.email
})

然后将 CustomAuthToken 类添加到您的 urls.py 中,例如 view

# urls.py
from django.urls import path
from . import views

urlpatterns += [
path(r'api-token-auth/', views.CustomAuthToken.as_view())
]

关于python - 覆盖 Django Rest 中的 authToken View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35266636/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com