Python使用redis-手机验证接口-发送短信验证

python使用redis

安装依赖

>: pip3 install redis

直接使用

import redis
r = redis.Redis(host='127.0.0.1', port=6379)

连接池的使用

import redis
pool = redis.ConnectionPool(host='127.0.0.1', port=6379)
r = redis.Redis(connection_pool=pool) 支持高并发

缓存使用:要额外的安装django_redis模块

在settings.py中进行配置使用
# 1.将缓存存储位置配置到redis中:settings.py
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {"max_connections": 100} # 开设池
        }
    }
}

# 2.操作cache模块直接操作缓存:views.py from django.core.cache import cache # 结合配置文件实现插拔式 # 存放token,可以直接设置过期时间 cache.set('token', 'header.payload.signature', 10) # 取出token token = cache.get('token')

手机验证接口,

  基于之前的二次封装短信验证,导入使用

from rest_framework.views import APIView
from .models import User
from utils.response import APIResponse
import re
# 注册逻辑:1.校验手机号是否存在 2.发送验证码 3.完成注册
class MobileAPIView(APIView):
    def post(self, request, *args, **kwargs):
        mobile = request.data.get('mobile')
        if not mobile or not re.match(r'^1[3-9]\d{9}$', mobile):
            return APIResponse(1, '数据有误')
        try:
            User.objects.get(mobile=mobile)
            return APIResponse(2, '已注册')
        except:
            return APIResponse(0, '未注册')

发送短信接口

# 发送验证码接口分析
from libs import txsms
from django.core.cache import cache
class SMSAPIView(APIView):
    def post(self, request, *args, **kwargs):
        # 1)拿到前台的手机号
        mobile = request.data.get('mobile')
        if not mobile or not re.match(r'^1[3-9]\d{9}$', mobile):
            return APIResponse(2, '数据有误')
        # 2)调用txsms生成手机验证码
        code = txsms.get_code()
        # 3)调用txsms发送手机验证码
        result = txsms.send_sms(mobile, code, 5)
        # 4)失败反馈信息给前台
        if not result:
            return APIResponse(1, '短信发送失败')
        # 5)成功服务器缓存手机验证码 - 用缓存存储(方便管理) - redis
        cache.set('sms_%s' % mobile, code, 5 * 60)
        # 6)反馈成功信息给前台
        return APIResponse(0, '短信发送成功')

猜你喜欢

转载自www.cnblogs.com/Gaimo/p/11768065.html