Justin-刘清政的博客

python/路飞项目/3-登录注册/7-短信注册接口

2020-03-02

后台

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
class RegisterSerializer(serializers.ModelSerializer):
code = serializers.CharField(min_length=4, max_length=4, required=True, write_only=True)
class Meta:
model = models.User
fields = ('mobile', 'password', 'code')
extra_kwargs = {
'password': {
'min_length': 8,
'max_length': 16,
'write_only': True,
}
}

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


def validate(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

def create(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
class RegisterViewSet(GenericViewSet, mixins.CreateModelMixin):
queryset = models.User.objects.all()
serializer_class = serializers.RegisterSerializer

def create(self, request, *args, **kwargs):
response = super().create(request, *args, **kwargs)
return APIResponse(result=response.data, http_status=response.status_code)
使用支付宝打赏
使用微信打赏

点击上方按钮,请我喝杯咖啡!

扫描二维码,分享此文章