settings配置:
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"CONNECTION_POOL_KWARGS": {"max_connections": 100},
}
}
}
视图函数:
import random
import re
from django.shortcuts import render
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response
from rest_framework.views import APIView
from django_redis import get_redis_connection
def phone_validator(value):
if not re.match(r"^(1[3|4|5|6|7|8|9])\d{9}$", value):
raise ValidationError('手机号格式错误')
class MessageSerializer(serializers.Serializer):
phone = serializers.CharField(label='手机号', validators=[phone_validator, ])
class MessageViews(APIView):
def get(self, request, *args, **kwargs):
# 1.校验手机号格式,获取手机号
ser = MessageSerializer(data=request.query_params)
if not ser.is_valid():
return Response({'status': False, 'message': '手机格式错误!'})
phone = ser.validated_data.get('phone')
print(phone)
# 2.生成随机验证码
random_code = random.randint(1000, 9999)
print(random_code)
# 3 搭建redis服务器
conn = get_redis_connection()
conn.set(phone, random_code, ex=30)
print(phone,random_code)
return Response({"status": True, "message": "验证码发送成功!"})
报错内容:
............
redis.exceptions.ConnectionError: Error 10061 connecting to 127.0.0.1:6379. 由于目标计算机积极拒绝,无法连接。.
[04/Jan/2023 11:08:00] "GET /api/message/?phone=18983900058 HTTP/1.1" 500 131154