Django开发_15_缓存

使用缓存可以大大提高程序的响应速度,增强用户体验。

缓存的方式有4种:数据库缓存,Redis缓存,Memcacheed缓存,程序级缓存

主要以数据库缓存和程序级缓存进行讲解

一、数据库缓存

(一)创建缓存表

终端输入命令,创建cache_table缓存表

python manage.py createcachetable cache_table

(二)添加缓存配置

settings.py:

CACHES = {
    # 数据库缓存
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'cache_table'  # 命令行:python manage.py createcachetable cache_table
    },}

(三)编写视图函数

views.py:

from django.core.cache import caches
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.cache import cache_page


def db_show(request):
    # 实例化缓存对象
    db_cache = caches["default"]
    # 判断缓存是否存在
    cache_data = db_cache.get("data_cache")  # 缓存的数据
    if cache_data:
        print("命中缓存")
        return HttpResponse(cache_data)
    print("没有命中,开始查找数据...")
    time.sleep(10)
    data = ["apple", "banana", "orange", "watermelon"]
    response = render(request, "fruits.html", {"data": data})
    # 设置缓存
    db_cache.set("data_cache", response.content, timeout=30)
    return response

配合urls.py,html文件展示

二、程序级缓存

(一)在视图函数中使用

views.py:

@cache_page(过期时间)

@cache_page(30)  # 装饰器(缓存过期时间)
def show(request):
    print("调用视图函数")
    data = ["apple", "banana", "orange", "watermelon"]
    return render(request, "fruits.html", {"data": data})

(二)在路由中使用

urls.py:

cache_page(过期时间)(视图函数)

path("pro_url/", cache_page(30)(url_show))

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值