编写注册接口
1 user/urls.py中添加路由
urlpatterns = [
path('register/', views.RegisterView.as_view()),# 注册视图, /user/register/
]
2 user/views.py 中写注册视图函数
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import datetime import random from django.http import HttpResponse from django_filters.rest_framework import DjangoFilterBackend from rest_framework import viewsets from rest_framework.authentication import BasicAuthentication, SessionAuthentication from rest_framework.filters import OrderingFilter from rest_framework.decorators import action from rest_framework.permissions import AllowAny, IsAdminUser, IsAuthenticatedOrReadOnly, IsAuthenticated from rest_framework.response import Response from rest_framework.throttling import UserRateThrottle from rest_framework.pagination import PageNumberPagination from rest_framework.views import APIView from rest_framework.permissions import BasePermission, SAFE_METHODS from user.models import User from user.serializers import UserSerializer, UserInfoSerializ class RegisterView(APIView): permission_classes = (AllowAny,) def post(self,request): """ 接收邮箱和密码, 前端校验两遍一致性, 注册成功后返回成功, 然后用户自行登录获取token 1. 随机用户名 2. 生成用户 3. 设置用户密码 4. 保存用户 :param request: :return: {'code':0,'msg':'注册成功'} """ email=request.data.get('email') password=request.data.get('password') if all([email,password]): pass else: return Response({'code':9999,'msg':'参数不全'}) rand_name=self.randomUsername() user=User(username=rand_name,email=email) user.set_password(password) user.save() return Response({'code':0,'msg':'注册成功'}) def randomUsername(self): d=datetime.datetime.now() base='SYL' time_str = '%04d%02d%02d%02d%02d' % (d.year, d.month, d.day, d.hour, d.minute) rand_num = str(random.randint(10000, 99999)) return base + time_str + rand_num
2 重写Django认证
2.1 syl/settings.py 中指定自定义后端认证函数位置
#自定义验证后端
AUTHENTICATION_BACKENDS = ['user.utils.EmailAuthBackend']
2.2user/utils.py 中重新认证函数
#以前使用username进行用户验证,现在改成email进行验证
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from .models import User class EmailAuthBackend: def authenticate(self,request,username=None,password=None): try: user=User.objects.get(username=username) except Exception as e: user=None if not user: try: user=User.objects.get(email=username) except Exception as e: user=None if user and user.check_password(password): return user else: return None def get_user(self,user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None
http://192.168.56.100:8888/user/register/