Redis-Django
windows安装部署
https://pythonav.com/wiki/detail/10/82/
启动redis
redis-server redis.conf
redis终端测试
redis-cli
auth 密码
安装模块
pip install django-redis
添加配置
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://10.211.55.28:6379", # 安装redis的主机的 IP 和 端口
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"CONNECTION_POOL_KWARGS": {
"max_connections": 1000,
"encoding": 'utf-8'
},
"PASSWORD": "foobared" # redis密码
}
}
}
测试
import redis
# 直接连接redis
conn = redis.Redis(host='127.0.0.1', port=6379, password='foobared', encoding='utf-8')
# 设置键值:15333333333="9999" 且超时时间为10秒(值写入到redis时会自动转字符串)
conn.set('15333333333', 9999, ex=10)
# 根据键获取值:如果存在获取值(获取到的是字节类型);不存在则返回None
value = conn.get('15333333333')
print(value)
视图中操作redis
from django.shortcuts import HttpResponse
from django_redis import get_redis_connection
def index(request):
# 去连接池中获取一个连接
conn = get_redis_connection("default")
# 设定值
conn.set('nickname', "心诩", ex=10)
# 获取值
value = conn.get('nickname').decode('utf-8')
print(value)
return HttpResponse("OK")