Django-cache-redis

1.创建app

python manage.py startapp booktest

2.安装富文本库

pip install django-redis-cache

3.setting添加booktest,配置文件存放位置


INSTALLED_APPS = [
    'multi_captcha_admin',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'booktest'
]

# 配置cache到redis
CACHES = {
    "default": {
        "BACKEND": "redis_cache.cache.RedisCache",
        "LOCATION": "localhost:6379",
        'TIMEOUT': 60,
    },
}

4.配置跟目录的文件夹中的urls

from django.contrib import admin
from django.urls import path, re_path
from django.conf.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('booktest/', include(('booktest.urls', 'booktest'), namespace='booktest'))
]

5.配置booktest/urls

from django.urls import path, re_path
from . import views

urlpatterns = [
    re_path(r'^cache1/$', views.cache1)

]

注:最新版本2.0以上使用path 或者re_path

6.编写views

# coding=utf-8
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from .models import *
from django.views.decorators.cache import cache_page
from django.core.cache import cache


# 缓存
@cache_page(60*10)
def cache1(request):
    return HttpResponse('hello1')
    # return HttpResponse('hello2')
    # cache.set('key1', 'value1', 600)
    # print(cache.get('key1'))
    # return render(request, 'booktest/cache1.html')
    # cache.clear()
    # return HttpResponse('ok')

7.redis操作
连接:redis-cli
切换数据库:select 1
查看键:keys *
查看值:get 键

 

作者: 温先生

嗨,我是温国力 ,Gerry是我的英文名。一名热衷于编程的开发者,主要专注于PHP、Python、go、区块链的开发。此博客编写了开发心得、读书心得、生活娱乐,随时等待你的关注。

发表评论