JWT 简单编写注册接口
1.1 user/urls.py 中添加路由
urlpatterns = [
path('register/', views.RegisterView.as_view()), # 注册视图, /user/register/
]
1.2 user/views.py 中写注册视图函数
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':999,'msg':"canshubuquan"}) rand_name=self.randomUsername() user=User(username=rand_name,email=email) user.set_password(password) user.save() return Response({'code':'0','msg':"sucessful"}) def randomUsername(self): """ 生成随机用户名: 格式: SYL + 年月日时分 + 5位随机数 :return: """ 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.2 user/utils.py 中重写认证函数
# -*- coding: utf-8 -*- from user.models import * 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
3.注册用户
3.1 注册接口测试
http://192.168.56.100:8888/user/register/
做最野的狼