手机注册接口

后台

urls.py
1
router.register('register', views.RegisterViewSet, 'register')
serializers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
classRegisterSerializer(serializers.ModelSerializer):
code = serializers.CharField(min_length=4, max_length=4, required=True, write_only=True)
classMeta:
model = models.User
fields = ('mobile', 'password', 'code')
extra_kwargs = {
'password': {
'min_length': 8,
'max_length': 16,
'write_only': True,
}
}

defvalidate_mobile(self, value):
if not re.match(r'^1[3-9][0-9]{9}$', value):
raise exceptions.ValidationError('mobile field error')
return value


defvalidate(self, attrs):
# 验证码校验 - 需要验证码与手机号两者参与
mobile = attrs.get('mobile')
code = attrs.pop('code')
old_code = cache.get(settings.SMS_CACHE_KEY % {'mobile': mobile})
if code != old_code:
raise exceptions.ValidationError({'code': 'double code error'})
else:
# 验证码的时效性:一旦验证码验证通过,代表改验证码已使用,需要立即失效
# cache.set(settings.SMS_CACHE_KEY % {'mobile': mobile}, '', -1)
pass

# 数据入库必须需要唯一账号:1)前台注册必须提供账号 2)默认用手机号作为账号名,后期可以修改
attrs['username'] = mobile

return attrs

defcreate(self, validated_data):# 入库的数据:mobile,password,username
return models.User.objects.create_user(**validated_data)
views.py
1
2
3
4
5
6
7
8
9
10
# 手机验证码注册
from rest_framework.viewsets import GenericViewSet
from rest_framework import mixins
classRegisterViewSet(GenericViewSet, mixins.CreateModelMixin):
queryset = models.User.objects.all()
serializer_class = serializers.RegisterSerializer

defcreate(self, request, *args, **kwargs):
response = super().create(request, *args, **kwargs)
return APIResponse(
status=1,msg=response.data,
http_status=response.status_code)

posted on 2020-12-16 21:21  Plyc  阅读(171)  评论(0编辑  收藏  举报

导航