gpt4 book ai didi

Django REST Framework 获取AuthToken 用户登录API View

转载 作者:行者123 更新时间:2023-12-05 00:58:09 24 4
gpt4 key购买 nike

你好 Django 社区,

当用户进行身份验证时,我想在 token 旁边发回电子邮件和用户 ID。我想我必须更改 UserLoginApiView 类,但我不知道如何重写 ObtainAuthToken 类来做到这一点。

有人有什么建议会很有帮助吗?

class UserLoginApiView(ObtainAuthToken):
"""Handle creating user authentication tokens"""
renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES

这是我在 Github 上的全部代码:https://github.com/KrestouferT/profiles-rest-api

最佳答案

docs它告诉您可以覆盖获取AuthToken中发布请求的返回响应:

If you need a customized version of the obtain_auth_token view, youcan do so by subclassing the ObtainAuthToken view class, and usingthat in your url conf instead.

For example, you may return additional user information beyond thetoken value:

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
})

在你的 urls.py 中:

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

关于Django REST Framework 获取AuthToken 用户登录API View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58588653/

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