redis之在django中使用
直接使用
- 在pool.py中创建连接池
import redis
POOL = redis.ConnectionPool(host='127.0.0.1', port=6379,password='1234',max_connections=1000)
- 在views.py中使用连接池连接
import redis
from django.shortcuts import render,HttpResponse
from utils.redis_pool import POOL
def index(request):
conn = redis.Redis(connection_pool=POOL)
conn.hset('kkk','age',18)
return HttpResponse('设置成功')
def order(request):
conn = redis.Redis(connection_pool=POOL)
conn.hget('kkk','age')
return HttpResponse('获取成功')
通过django缓存命令(在django中推荐)
- 安装
pip install django-redis
- 在配置文件中添加配置
# redis配置
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}
# "PASSWORD": "123",
}
}
}
- 在视图函数中通过django内存方法调用
django缓存使用方法见: https://www.cnblogs.com/smyz/p/17482999.html
# 此时再使用django的缓存命令,就会直接存储到redis中了
cache.get('xxx')
cache.set('xxx')
通过django-redis模块提供的命令
- 安装
pip install django-redis
- 使用方法
from django_redis import get_redis_connection
def test_redis(request):
conn = get_redis_connection()
res = conn.get('key')
print(res
return JsonResponse(xxxxxxxxx)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类