短信注册接口

后台

urls.py
router.register('register', views.RegisterViewSet, 'register')
serializers.py
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
# 手机验证码注册
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)

你可能感兴趣的:(线上卖课系统,vue.js,elementui,python,前端,javascript)