二 .redis在django中使用

一 .redis在django中使用(缓存)

https://www.cnblogs.com/wupeiqi/articles/5246483.html

1. 方式一 自定义(通过连接池)

redis_pool.py

import
redis Pool= redis.ConnectionPool(host='localhost', port=6379)
urls.py

from
django.contrib import admin from django.urls import path from myapp import views urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.index), path('home/', views.home), ]
views.py

from
django.shortcuts import render,HttpResponse import redis from uits.redis_pool import # Pool 引入连接池 def index(request): conn = redis.Redis(connection_pool=Pool) conn.hset("k1","age",18) return HttpResponse("这是设置值") def home(request): conn = redis.Redis(connection_pool=Pool) aa=conn.hget("k1","age") print(aa) return HttpResponse("获取值")

 2. 方式二  (通过第三方模块)

Redis缓存(依赖:pip3 install django-redis)

settings.py中

#
redis缓存配置 CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis:localhost", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "CONNECTION_POOL_KWARGS": {"max_connections": 100} # "PASSWORD": "密码", } }, "redis2": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis:localhost", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "CONNECTION_POOL_KWARGS": {"max_connections": 100} # "PASSWORD": "密码", } } }
views.py

from
django.shortcuts import render,HttpResponse import redis from django_redis import get_redis_connection def index(request): conn = get_redis_connection("default") # 表示redis名称 在settings 中 conn.hset("k1","age",18) return HttpResponse("这是设置值") def home(request): conn = get_redis_connection("redis1") aa=conn.hget("k1","age") print(aa) return HttpResponse("获取值")

 3. 方式三  全站缓存  (通过自带中间件  全局)

settings.py


MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', # 全局使用redis缓存 这个中间件时py自带子需要添加上 位置必须(一头一尾) 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', # 全局使用redis缓存 这个中间件时py自带子需要添加上 位置必须(一头一尾) ] # redis缓存配置 CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis:localhost", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "CONNECTION_POOL_KWARGS": {"max_connections": 100} # "PASSWORD": "密码", } }, "redis2": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis:localhost", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "CONNECTION_POOL_KWARGS": {"max_connections": 100} # "PASSWORD": "密码", } } }


其他设置
 CACHE_MIDDLEWARE_ALIAS = ""
 CACHE_MIDDLEWARE_SECONDS = ""
 CACHE_MIDDLEWARE_KEY_PREFIX = ""



views.py 

from
django.shortcuts import render,HttpResponse import time def index(request): ctime=str(time.time()) return HttpResponse("这是设置值",ctime) def home(request): ctime = str(time.time()) return HttpResponse("获取值",ctime)

 4. 方式四  单视图缓存 (添加装饰器)

# redis缓存配置
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis:localhost",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {"max_connections": 100}
            # "PASSWORD": "密码",
        }
    }
 
}
views.py

from
django.shortcuts import render,HttpResponse import time from django.views.decorators.cache import cache_page # 比全站优先级高 # @cache_page(60 * 15) # 后面参数是时间 def index(request): ctime=str(time.time()) return HttpResponse("这是设置值",ctime) def home(request): ctime = str(time.time()) return HttpResponse("获取值",ctime)
    对某个url进行单视图缓存

from django.views.decorators.cache import cache_page urlpatterns = [ url(r'^foo/([0-9]{1,2})/$', cache_page(60 * 15)(my_view)), ]

5. 方式五  局部视图  缓存 (需要自己定义  就是一个视图中某一个地方需要缓存)

settings.py

#
redis缓存配置 CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis:localhost", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "CONNECTION_POOL_KWARGS": {"max_connections": 100} # "PASSWORD": "密码", } } }
views.py

from
django.shortcuts import render,HttpResponse import time def index(request): return render(request,'aa.html') def home(request): ctime = str(time.time()) return HttpResponse("获取值",ctime)
 aa.html



{% load cache %}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul> <li>1111111111111111111</li> <li>2222222222222222222</li> <li> {% cache 5000 aaaaaa %} {# {% cache 5000 缓存key %} 这个key值可以是随意字符串#} 缓存内容66666666666666666666666666666(时间5000秒) {% endcache %} </li> </ul> </body> </html>
原文地址:https://www.cnblogs.com/lovershowtime/p/11717032.html