记录DRF实战中的一些技巧
一:redis的存储与获取,以及管道的应用减少连接次数
- 导入库
from django_redis import get_redis_connection
- 创建连接 (verify_codes是配置里连接的哪个redis?)
edis_conn = get_redis_connection(‘verify_codes’)
- 从redis中获取
send_flag = redis_conn.get(“send_flag_%s” % mobile)
- 创建管道,一次连接进行多次存取
#创建 redis管道(把多次的redis操作装入到管道中,将来一次性的执行,减少redis链接操作
pl = redis_conn.pipeline()
# 将验证码装到管道中
pl.setex(‘sms_%s’ % mobile, CL.SMS_CODE_REDIS_EXPIRES, sms_code)
# 存储一个标记
pl.setex(‘send_flag_%s’ % mobile, CL.SEND_SMS_CODE_INIERVAL, 1)
# 执行管道
pl.execute()
代码示例:
from django.shortcuts import render
from rest_framework.views import APIView
from random import randint
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework import status
from django.http import HttpResponse
from . import constants as CL
import logging
# Create your views here.
class SMSCodeView(APIView):
'''短信验证'''
def get(self, request, mobile):
# 1. 创建redis链接对象
redis_conn = get_redis_connection('verify_codes')
# 2. 从redis获取 发送的标记
send_flag = redis_conn.get("send_flag_%s" % mobile)
if send_flag:
return Response({'message': '手机号频繁发送短信'}, status=status.HTTP_400_BAD_REQUEST)
# 3. 生成验证码
sms_code = '%06d' % randint(0, 999999)
logging.info(sms_code)
# 4. 把验证码存放到redis数据库
# 创建 redis管道(把多次的redis操作装入到管道中,将来一次性的执行,减少redis链接操作)
pl = redis_conn.pipeline()
# 将验证码装到管道中
pl.setex('sms_%s' % mobile, CL.SMS_CODE_REDIS_EXPIRES, sms_code)
# 存储一个标记
pl.setex('send_flag_%s' % mobile, CL.SEND_SMS_CODE_INIERVAL, 1)
# 执行管道
pl.execute()
# 5. 响应
return Response({'message': 'ok'})
二:Celery实现高并发的操作
- 在根项目下新建celery_taks文件夹(>>config.py与main.py文件)
1)main函数代码from celery import Celery #1.创建celery实例对象 celery_app = Celery('manba') #2.加载配置文件 celery_app.config_from_object('celery_tasks.config') #3.自动注册异步任务 celery_app.autodiscover_tasks(['celery_tasks.sms'])
- config函数
# celery配置文件 #指定任务队列的位置 broker_url = "redis://49.232.23.70:6379/7"
- 新建异步文件例如(里面都是tasks文件)
1)tasks文件(这个文件名不能被修改)# 编写异步任务 from celery_tasks.main import celery_app @celery_app.task(name='send_sms_code') # 使用装饰器注册任务 def send_sms_code(): print('77777777777777') import time time.sleep(5) print('77777777777777')
- 运行
celery -A celery_tasks.main worker -l info
在视图内使用
#导包
from celery_tasks.sms.tasks import send_sms_code
class SMSCodeView(APIView):
...
# 调用模拟异步操作
print('-'*7)
send_sms_code.delay()
print('-'*7)
# 5. 响应
return Response({'message': 'ok'})