redis之在django中使用

直接使用

  1. 在pool.py中创建连接池
import redis
POOL = redis.ConnectionPool(host='127.0.0.1', port=6379,password='1234',max_connections=1000)
  1. 在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中推荐)

  1. 安装
pip install django-redis
  1. 在配置文件中添加配置
# 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",
        }
    }
}
  1. 在视图函数中通过django内存方法调用

django缓存使用方法见: https://www.cnblogs.com/smyz/p/17482999.html

# 此时再使用django的缓存命令,就会直接存储到redis中了 
cache.get('xxx')
cache.set('xxx')

通过django-redis模块提供的命令

  1. 安装
pip install django-redis
  1. 使用方法
from django_redis import get_redis_connection
def test_redis(request):
    conn = get_redis_connection()
    res = conn.get('key')
    print(res
    return JsonResponse(xxxxxxxxx)
posted @   树苗叶子  阅读(31)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类
点击右上角即可分享
微信分享提示