redis之django-redis的簡單緩存使用
本文介紹了redis之django-redis的簡單緩存使用,分享給大家,具體如下:
自定義連接池
這種方式跟普通py文件操作redis一樣,代碼如下:
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('設(shè)置成功') def order(request): conn = redis.Redis(connection_pool=POOL) conn.hget('kkk','age') return HttpResponse('獲取成功')
通過第三方組件操作redis
安裝
pip3 install django-redis
配置
settings.py
# 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": "密碼", } } }
使用
views.py
import redis from django.shortcuts import render,HttpResponse from django_redis import get_redis_connection def index(request): conn = get_redis_connection("default") return HttpResponse('設(shè)置成功') def order(request): conn = get_redis_connection("default") return HttpResponse('獲取成功')
全站緩存
使用中間件,經(jīng)過一系列的認(rèn)證等操作,如果內(nèi)容在緩存中存在,則使用FetchFromCacheMiddleware獲取內(nèi)容并返回給用戶,
當(dāng)返回給用戶之前,判斷緩存中是否已經(jīng)存在,如果不存在則UpdateCacheMiddleware會將緩存保存至緩存,從而實(shí)現(xiàn)全站緩存
MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', # 其他中間件... 'django.middleware.cache.FetchFromCacheMiddleware', ]
一個放在最上面,一個放在最下面
views.py
from django.shortcuts import render,HttpResponse import time def index(request): ctime = str(time.time()) return HttpResponse(ctime) def order(request): ctime = str(time.time()) return HttpResponse(ctime)
配置了全站緩存,在不同的時間(一定范圍內(nèi)),上面兩個視圖返回的時間是一樣的,都是緩存時的時間
單獨(dú)視圖緩存
方式一:通過裝飾器
from django.views.decorators.cache import cache_page @cache_page(60 * 15) def my_view(request): ...
方式二:通過url
from django.views.decorators.cache import cache_page urlpatterns = [ url(r'^foo/([0-9]{1,2})/$', cache_page(60 * 15)(my_view)), ]
局部頁面緩存
1. 引入TemplateTag
{% load cache %}
2. 使用緩存
{% cache 5000 緩存的key %} 緩存內(nèi)容 {% endcache %}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python實(shí)戰(zhàn)之實(shí)現(xiàn)簡易的學(xué)生選課系統(tǒng)
又到了小伙伴們最喜歡的python實(shí)戰(zhàn)環(huán)節(jié),文中對實(shí)現(xiàn)簡易的學(xué)生選課系統(tǒng)作了非常詳細(xì)的代碼示例,對正在學(xué)習(xí)python的小伙伴們有很好的幫助,需要的朋友可以參考下2021-05-05Python 爬蟲之Beautiful Soup模塊使用指南
這篇文章主要介紹了Python 爬蟲之Beautiful Soup模塊使用指南,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07Pytorch實(shí)現(xiàn)WGAN用于動漫頭像生成
這篇文章主要介紹了Pytorch實(shí)現(xiàn)WGAN用于動漫頭像生成,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03關(guān)于python實(shí)現(xiàn)json/字典數(shù)據(jù)中所有key路徑拼接組合問題
這篇文章主要介紹了關(guān)于python實(shí)現(xiàn)json/字典數(shù)據(jù)中所有key路徑拼接組合問題,文中有詳細(xì)的代碼說明,需要的朋友可以參考下2023-04-04