20-后台短信注册接口
后台短信注册接口
urls.py
from django.urls import path, include
from rest_framework.routers import SimpleRouter
from . import views
router = SimpleRouter()
router.register('',
router.register('register', views.RegisterView, 'register') # /user/register/ post请求就是新增
urlpatterns = [
path('', include(router.urls)),
]
serializer.py
# 注册账户
class Registerserializers(serializers.ModelSerializer):
# 前端字段:用户名、密码、验证码
code = serializers.CharField(max_length=4, min_length=4, write_only=True)
class Meta:
model = models.User
fields = ['telephone', 'password', 'code', 'username']
extra_kwargs = {
'password': {'max_length': 18, 'min_length': 8},
'username': {'read_only': True},
}
def validate(self, attrs):
telephone = attrs.get('telephone')
code = attrs.get('code')
# 先校验验证码是否匹配
cache_code = cache.get(settings.PYTHON_CACHE_KEY.format(telephone))
if re.match('^1[3-9][0-9]{9}$', telephone): # 手机号码格式正确
if code == cache_code: # 验证码正确,能进到这就说明一切注册流程全部无误
attrs['username'] = 'luffy_' + telephone
attrs.pop('code') # 因为code字段在数据库中没有,所以需要去除
return attrs
else:
raise ValidationError("验证码错误!")
else:
raise ValidationError("手机号码格式不正确!")
def create(self, validated_data):
user = models.User.objects.create_user(**validated_data)
return user
views.py
class RegisterView(GenericViewSet, CreateModelMixin):
queryset = models.User.objects.all()
serializer_class = serializer.Registerserializers
# 此处需要重写CreateModelMixin中的create方法,因为CreateModelMixin中create返回的数据格式不是我们想要的
def create(self, request, *args, **kwargs):
response = super().create(request, *args, **kwargs) # 这里只处理整个注册逻辑全部正确的逻辑,错误的逻辑在CreateModelMixin中的create方法已经处理了
username = response.data.get('username')
return APIResponse(code=1, msg='Successful', username=username)