-
编写注册接口
-
user/urls.py 中添加路由
-
urlpatterns = [ path('register/', views.RegisterView.as_view()), # 注册视图, /user/register/ ]
-
-
user/views.py 中写注册视图函数
-
import datetime import random 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') passwrod = request.data.get('password') if all([email, passwrod]): pass else: return Response({'code': 9999, 'msg': '参数不全'}) rand_name = self.randomUsername() user = User(username=rand_name, email=email) user.set_password(passwrod) user.save() return Response({'code': 0, 'msg': '注册成功'}) 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
-
-
-
重写django认证
-
syl/settings.py 中指定自定义后端认证函数位置
-
AUTHENTICATION_BACKENDS = ['user.utils.EmailAuthBackend']
-
-
user/utils.py 中重写认证函数
-
# 以前使用username进行用户验证,现在修改成email进行验证 class EmailAuthBackend: # 自定义权限类 # permission_classes = (MyPermission,) # 自定义认证类, 自定义会覆盖全局配置 # authentication_classes = (JSONWebTokenAuthentication,) def authenticate(self, request, username=None, password=None): try: user = User.objects.get(username=username) except Exception as e: print(e) user = None if not user: try: user = User.objects.get(email=username) except Exception as e: print(e) user = None if user and user.check_password(password): # jwt_response_payload_handler() 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/
-
-
-
获取用户列表接口测试
-
-