Django 快取原理 與新增 redis 快取

2022-04-01 01:17:50 字數 3485 閱讀 2037

#新建立 應用 stu

#修改settings.py,增加快取配置

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'stu'

]#末尾增加(記憶體快取):

caches =

}cache_middleware_key_prefix = ''

cache_middleware_seconds = 600

cache_middleware_alias = 'default'

#修改urls.py

url(r'^class/',include('stu.urls'))

#修改

stu/urls.py

#coding=utf-8

from django.conf.urls import url

import views

urlpatterns = [

url(r'^$',views.index_view)

]#增加models.py

# -*- coding: utf-8 -*-

from __future__ import unicode_literals

from django.db import models

# create your models here.

class clazz(models.model):

cname = models.charfield(max_length=30,unique=true)

def __unicode__(self):

return u'clazz:%s'%self.cname

#資料庫新添兩條資料

#修改 views.py

#匯入 django 快取包

from django.core.cache import caches

# create your views here.

#獲取快取物件

cacheobj = caches['default']

def cache_view(fund):

def _wur(request,*args,**kwargs):

#path 為鍵,get 鍵後為內容 value

data = cacheobj.get(request.path)

if data:

print '讀取快取資料'

print '準備獲取資料庫資料'

response = fund(request,*args,**kwargs)

print '進行快取資料'

cacheobj.set(request.path,response.content)

return response

return _wur

#新增裝飾器

@cache_view

def index_view(request):

postlist = clazz.objects.all()

return render(request,'index.html',)

#模板檔案 index.html

}效果如下: 訪問 檢視控制台

# 修改settings.py 增加redis 快取配置 ,127.0.0.1:6379/0 代表 redis 本地位址, 0 表示使用redis 0號庫

caches = ,

'redis':

}cache_middleware_key_prefix = ''

cache_middleware_seconds = 600

cache_middleware_alias = 'redis'

# 修改views.py 將 default 本地快取改為 redis 快取 cacheobj = caches['redis']

from django.core.cache import caches

# create your views here.

#獲取快取物件

cacheobj = caches['redis']

print cacheobj

def cache_view(fund):

def _wur(request,*args,**kwargs):

data = cacheobj.get(request.path)

if data:

print '讀取快取資料'

print '準備獲取資料庫資料'

response = fund(request,*args,**kwargs)

print '進行快取資料'

cacheobj.set(request.path,response.content)

return response

return _wur

@cache_view

def index_view(request):

postlist = clazz.objects.all()

print request.path

print request.method

return render(request,'index.html',)

# 同樣通過訪問 已經把 /class/ 以及頁面結果插入到 redis 庫中,截圖顯示, treenms是用來檢視 redis 中 value 的軟體

PHP Cache快取機制與檔案快取原理

php cache快取機制與檔案快取原理,使用 pear 中的 cache 可以將內容快取於檔案,資料庫或者記憶體中,以檔案為例。沒有使用快取 pear content cache1.php php echo 這是內容。p echo 當前時間是 date m d y h i s a time br ...

django快取設定與驗證碼

安裝快取模組 pip install django redis 4.12.1 在settings中配置 快取配置 caches django session存 reidis 1 號庫 現在基本不需要使用 session 圖形驗證碼,存redis 2號庫 img code 配置session使用red...

memcache 記憶體機制與快取原理

如果用 c 語言直接 malloc,free 來向作業系統申請和釋放記憶體時,在不斷的申請和釋放過程中,形成了一些很小的記憶體片斷,無法再利用.這種空閒,但無法利用記憶體的現象,稱為記憶體的碎片化.memcached 用 slab allocator 機制來管理記憶體.slab allocator ...