28 django使用redis


django 使用redis

依赖
>: pip3 install redis

一、通用操作(跟框架无关)

1. utils/redis_pool.py

# 写一个py文件
import redis
POOL = redis.ConnectionPool(host='127.0.0.1', port=6379, max_connections=100)

2.  导入,使用user/views.py


from utils.redis_pool import POOL
import redis
def home(request):
     conn=redis.Redis(connection_pool=POOL)
     conn.set('name','htt')
     conn.close()
     return render(request,"index.html")

配上路由,此时访问http://127.0.0.1:8000/backend/,到redis查看会发现,redis有一条数据,name 对应这htt

二、使用django-redis

1. 安装  pip install django-redis

2.settings/dev.py配置上配置文件

 redis配置,一旦这样配置,django中的缓存,也可以用redis
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/0",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {"max_connections": 100},
            "DECODE_RESPONSES": True,
            # "PASSWORD": "",
        }
    }
   
}

3.使用user/views.py(直接使用conn对象)

from django_redis import get_redis_connection
def home(request):
    conn=get_redis_connection('default')
    conn.set('age','18')
    return render(request,"index.html")

此时,访问http://127.0.0.1:8000/backend/,再查看redis,会多出age 对应18

三、如果以后在django 中使用,建议使用这种方法

需要额外安装django-redis

1.settings/dev.py配置上配置文件,将缓存存储位置配置到redis中

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/0",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {"max_connections": 100},
            "DECODE_RESPONSES": True,
            # "PASSWORD": "",
        }
    }
   
}

2.使用user/views.py

# 也会存到redis中,最大的好处,cache.set的value值,可以是python的任意类型对象
from django.core.cache import cache     #结合配置文件实现插拔式
def home(request): cache.
set('hobby',['篮球','足球']) #操作cache模块,直接操作缓存 res=cache.get('hobby')
print(res)
return render(request,'index.html')
# cache帮咱们做了封装,可以缓存任意的python对象 # django缓存的内部,拿到对象转成了二进制(pickle),存到了redis中