day11 luffy之手机是否存在验证接口
一、手机号验证接口
1、user/urls.py
from django.urls import path
from rest_framework.routers import SimpleRouter
from . import views
router = SimpleRouter()
router.register('', views.LoginViewSet, 'login')
urlpatterns = [
]
urlpatterns += router.urls
2、user/views.py
from rest_framework.viewsets import ViewSet
from . import serializers, models
from luffyapi.utils.response import APIResponse
from rest_framework.decorators import action
class LoginViewSet(ViewSet):
# 局部禁用认证、权限组件
authentication_classes = ()
permission_classes = ()
@action(methods=['POST'], detail=False)
def login(self, request, *args, **kwargs):
serializer = serializers.LoginSerializer(data=request.data, context={'request': request})
if serializer.is_valid():
token = serializer.context.get('token')
user = serializer.context.get('user')
result = serializers.LoginSerializer(user, context={'request': request}).data
result['token'] = token # id,username,icon,token
return APIResponse(result=result)
return APIResponse(1, serializer.errors)
# 验证手机号是否存在,放到一个类写了,有多种验证方法
@action(methods=['GET'], detail=False)
def check_telephone(self, request, *args, **kwargs):
import re
telephone = request.query_params.get('telephone')
if not re.match('^1[3-9][0-9]{9}', telephone):
return APIResponse(code=0, msg='手机号不合法')
try:
# 手机号合法就会返回True
models.User.objects.get(telephone=telephone)
return APIResponse(code=1) # code等于1是验证成功
except:
# 手机号合法就会返回False
return APIResponse(code=0, msg='手机号不存在')
3、验证手机号是否存在(另一种方式)
from rest_framework.viewsets import ViewSet
from luffy.utils.response import APIResponse
from .models import User
from rest_framework.decorators import action
from rest_framework.exceptions import APIException
class UserView(ViewSet):
@action(methods=['POST'], detail=False )
def check_phone(self, request, *args, **kwargs):
telephone = request.data.get('telephone')
try:
User.objects.get(telephone=telephone) # 有且只有一个才行,否则报错
except Exception as e:
raise APIException('该手机号不存在')
return APIResponse(is_exist=True)