快速入手-基于Django-rest-framework的第三方认证插件(SimpleJWT)权限认证扩展返回用户等其他信息(十一)

发布于:2025-04-02 ⋅ 阅读:(20) ⋅ 点赞:(0)

1、修改serializer.py,增加自定义类

# 自定义用户登录token等返回信息

class MyTokenObtainPair(TokenObtainPairView):

    def post(self, request, *args, **kwargs):

        serializer = self.get_serializer(data=request.data)

        try:

            serializer.is_valid(raise_exception=True)

        except TokenError as e:

            raise InvalidToken(e.args[0])

        # 获取所有值

        result = serializer.validated_data

        result["email"] = serializer.user.email

        result["username"] = serializer.user.username

        result["id"] = serializer.user.id

        # 重写token名字

        result["token"] = result.pop("access")

        return Response(result, status=status.HTTP_200_OK)

完整代码:

from django.shortcuts import render, HttpResponse
from rest_framework.views import APIView

from .models import Link

from rest_framework import serializers, status
from rest_framework.response import Response
from rest_framework_simplejwt.exceptions import TokenError, InvalidToken
from rest_framework_simplejwt.views import TokenObtainPairView


# 和模型直接耦合,确定不灵活,上面的是自己写
class LinkSerializer(serializers.ModelSerializer):
    # 自定义接口字段名称source="name"是真实的,mingzi是解耦的名称
    mingzi = serializers.CharField(max_length=300, source="name")

    class Meta:
        # 指定关联哪个模型集
        model = Link
        # fields = "__all__"
        # 排除去掉哪些字段
        exclude = ["gid", "name"]


# 自定义用户登录token等返回信息
class MyTokenObtainPair(TokenObtainPairView):

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        try:
            serializer.is_valid(raise_exception=True)
        except TokenError as e:
            raise InvalidToken(e.args[0])

        # 获取所有值
        result = serializer.validated_data
        result["email"] = serializer.user.email
        result["username"] = serializer.user.username
        result["id"] = serializer.user.id
        # 重写token名字
        result["token"] = result.pop("access")
        return Response(result, status=status.HTTP_200_OK)

2、修改api模块中的urls.py

    # 登录

    # path("token/", TokenObtainPairView.as_view(), name="token_obtain_pair"),

    path("token/", serializer.MyTokenObtainPair.as_view(), name="token_obtain_pair"),

完整代码

from django.urls import path, re_path
from . import views

from . import serializer

from rest_framework import routers
from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
    TokenVerifyView,
    TokenBlacklistView,
)

routers = routers.DefaultRouter()
routers.register("linkapi", views.Linkapi)

app_name = "api"
urlpatterns = [
    # 登录
    # path("token/", TokenObtainPairView.as_view(), name="token_obtain_pair"),
    path("token/", serializer.MyTokenObtainPair.as_view(), name="token_obtain_pair"),
    # 刷新
    path("token/refresh/", TokenRefreshView.as_view(), name="token_refresh"),
    # 校验
    path("token/verify/", TokenVerifyView.as_view(), name="token_verify"),
    # 黑名单
    path("token/blacklist/", TokenBlacklistView.as_view(), name="token_blacklist"),
]

urlpatterns += routers.urls

3、基于上一节的代码,其他代码不变 

4、测试

 

 


网站公告

今日签到

点亮在社区的每一天
去签到