django的用户管理与token认证
from django.contrib.auth.models import User
from django.shortcuts import render
from rest_framework import generics, authentication, permissions
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import UserSerializer
class RegisterView(generics.CreateAPIView):
"""
用户注册视图
"""
queryset = User.objects.all()
serializer_class = UserSerializer
class LoginView(APIView):
"""
用户登录视图
"""
def post(self, request, *args, **kwargs):
username = request.data.get("username")
password = request.data.get("password")
user = authenticate(request, username=username, password=password)
if user is not None:
token, created = Token.objects.get_or_create(user=user)
return Response({"token": token.key})
else:
return Response({"error": "登录失败"}, status=400)
class UserDetailView(generics.RetrieveAPIView):
"""
用户详情视图
"""
queryset = User.objects.all()
serializer_class = UserSerializer
authentication_classes = (authentication.TokenAuthentication,)
permission_classes = (permissions.IsAuthenticated,)
这个代码实例提供了用户注册、登录以及用户详情的视图。注册视图使用了CreateAPIView
来处理创建用户的请求,登录视图是一个标准的APIView
,它检查用户凭证并返回一个访问令牌,用户详情视图则要求用户已经通过了认证,并且使用了Token认证。
评论已关闭