一.配置文件settings.py中

# 设置django缓存存放位置为redis数据库,并设置一个默认(default)选项,在redis中(配置文件/etc/redis/redis.conf)开启了RDB持久化储存
# pip install django-redis, 然后在视图中可以通过 from django_redis import get_redis_connection 这个方法和redis数据库进行连接
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
# redis服务器的ip地址及端口号,及数据库序号,redis一共有15个数据库 0~15
"LOCATION": "redis://127.0.0.1:6379/6",
     # "LOCATION": "redis://:passwordpassword@47.193.146.xxx:6379/0", # 如果redis设置密码的话,需要以这种格式进行设置,host前面是密码
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
}

二.某个应用的视图文件views.py中

from django.shortcuts import render, redirect
from django.views.generic import View
from goods.models import GoodsType, IndexGoodsBanner, IndexPromotionBanner, IndexTypeGoodsBanner, GoodsSKU
from order.models import OrderGoods
from django_redis import get_redis_connection # 使用该模块的方法, 可以设置和取出缓存(缓存一些无须用户登录就可以获取的数据)
# 保存缓存的载体已经在settings中设置成redis
from django.core.cache import cache from django.core.urlresolvers import reverse
from django.core.paginator import Paginator # http://127.0.0.1:8000/index
class IndexView(View):
"""首页"""
def get(self, request):
"""显示网页"""
  # 每次来自浏览器首页的请求,都先尝试获取缓存
  context = cache.get('index_page_data')
    # 删除缓存
    # cache.delete("键名")
if context is None:
# 获取商品分类信息, 有那几大类商品
types = GoodsType.objects.all() # 获取首页轮播商品的信息
index_banner = IndexGoodsBanner.objects.all().order_by('index') # 获取首页促销活动的信息
promotion_banner = IndexPromotionBanner.objects.all().order_by('index') # 获取首页分类商品活动的信息
# types_goods_banner = IndexTypeGoodsBanner.objects.all()
for type in types:
# 根据type查询type种类首页展示的文字商品信息和图片商品信息
title_banner = IndexTypeGoodsBanner.objects.filter(type=type, display_type=0).order_by('index')
image_banner = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1).order_by('index')
# 给type对象增加两个属性title_banner, image_banner
# 分别保存type种类首页展示的文字商品信息和图片商品信息
type.title_banner = title_banner
type.image_banner = image_banner # 将购物车显示数量设置为零
cart_count = 0 # 组织缓存的上下文
context = {
'types': types,
'index_banner': index_banner,
'promotion_banner': promotion_banner,
'cart_count': cart_count
}
# 设置缓存, 第一个参数是键名,第二个值,第三个是过期时间, 不设置过期时间,就是永不过期
cache.set('index_page_data', context, 3600)# 获取登录用户后购物车商品的数目,先设置为零
cart_count = 0
# 获取user
user = request.user
if user.is_authenticated():
# 用户已登录
conn = get_redis_connection('default')
cart_key = 'cart_%d'%user.id
cart_count = conn.hlen(cart_key)
# 更新模板上下文
context.update(cart_count=cart_count)
# 使用模板
return render(request, 'index.html', context)

这里既使用cache模块将数据保存到redis中(已经在配置文件中将缓存数据库设置为了redis), 也使用了django_redis模块的get_redis_connection()方法进行保存数据, 个人理解:缓存这里和redis肯定建立的是长连接,使用get_redis_connection()可能建立的是短链接。但是直接使用cache,只可以使用cache,get()进行获取数据, 使用cache.set()进行设置缓存. 但是,使用get_redis_connection(),可以自由使用redis的各种数据格式进行保存数据,更加灵活多变.

Django 项目中设置缓存的更多相关文章

  1. Django项目中使用Redis

    Django项目中使用Redis DjangoRedis 1 redis Redis 是一个 key-value 存储系统,常用于缓存的存储.django-redis 基于 BSD 许可, 是一个使 ...

  2. 谈谈MVC项目中的缓存功能设计的相关问题

    本文收集一些关于项目中为什么需要使用缓存功能,以及怎么使用等,在实际开发中对缓存的设计的考虑 为什么需要讨论缓存呢? 缓存是一个中大型系统所必须考虑的问题.为了避免每次请求都去访问后台的资源(例如数据 ...

  3. Django 1.6 最佳实践: 如何设置django项目的设置(settings.py)和部署文件(requirements.txt)

    Django 1.6 最佳实践: 如何设置django项目的设置(settings.py)和部署文件(requirements.txt) 作者: Desmond Chen,发布日期: 2014-05- ...

  4. [翻译]在Django项目中添加谷歌统计(Google Analytics)

    原文:<Google Analytics tracking code into Django projects, the easy way> 对我来说,制作一个可扩展的Django应用随时 ...

  5. 擦他丫的,今天在Django项目中引用静态文件jQuery.js 就是引入报错,终于找到原因了!

    擦 ,今天在Django项目中引用静态文件jQuery.js 就是引入报错,终于找到原因了! 问题在于我使用的谷歌浏览器,默认使用了缓存,导致每次访问同一个url时,都返回的是缓存里面的东西.通过谷歌 ...

  6. django 项目中使用多数据库 multiple databases

    假如在一个django项目中使用到了不只一个数据库, 其实这在大一点的工程中很常见,比如主从库 那么会涉及到如下一些东西 1, 定义 在settings中的DATABASE中定义会使用到的数据,比如除 ...

  7. django 项目中的 favicon.ico 处理

    django 项目中的 favicon.ico 处理  (django == 2.0.6) 1. 引入模块: from django.views.generic.base import Redirec ...

  8. Django项目中"expected str, bytes or os.PathLike object, not list"错误解决:

    对于这个错误,也在于自己对django基础的掌握不是很牢固,忽略了MEDIA_ROOT的类型是string,而不是list. 错误的写法: MEDIA_ROOT = [ os.path.join(BA ...

  9. 【技术博客】JWT的认证机制Django项目中应用

    开发组在开发过程中,都不可避免地遇到了一些困难或问题,但都最终想出办法克服了.我们认为这样的经验是有必要记录下来的,因此就有了[技术博客]. JWT的认证机制Django项目中应用 这篇技术博客基于软 ...

随机推荐

  1. Problem B. Market(market.c/cpp/pas)

    Problem B. Market(market.c/cpp/pas)Time limit: 1 secondsMemory limit: 128 megabytes在比特镇一共有 n 家商店,编号依 ...

  2. Proximal Algorithms

    1. Introduction Much like Newton's method is a standard tool for solving unconstrained smooth minimi ...

  3. 替换SQL执行计划

    Switching two different SQL Plan with SQL Profile in Oracle... 当SQL是业务系统动态生成的,或者是第三方系统产生的,在数据库层面分析发现 ...

  4. VUE(现代库) VS jquery(传统库)

      众所周知最近几年前端发展非常的迅猛,除各种框架如:backbone.angular.reactjs外,还有模块化开发思想的实现库:sea.js .require.js .webpack以及 前端上 ...

  5. MFC框架仿真<二>

  6. (并查集)A Bug's Life -- POJ -- 2492

    链接: http://poj.org/problem?id=2492 http://acm.hust.edu.cn/vjudge/contest/view.action?cid=82830#probl ...

  7. java基础-day5

    第05天 java基础知识 今日内容介绍 u 方法的概述及基本使用 u 方法的练习及注意事项 u 方法的重载及参数传递 u 方法的操作数组的练习 第1章   方法的概述及基本使用 1.1  方法定义格 ...

  8. Zend Studio 安装破解和汉化

    1.下载文件. 2.默认安装Zend Studio. 3.替换安装目录下plugins下的com.zend.verifier_12.5.1.v20150514-2003.jar文件 4.打开Zend ...

  9. Postman - 測試 API 的好工具

    POSTMAN in Google APP Store 因為工作的關係,常常寫一些 API 供 APP 使用.以前傻傻的,每次測試的時候都會自己刻一個 HTML 的表單,一個一個填入 input ,接 ...

  10. What if you are involved in an automobile accident in the US

    What if you are involved in an automobile accident in the US With increasing Chinese tourists and vi ...