博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
django cache的简单使用
阅读量:4300 次
发布时间:2019-05-27

本文共 1121 字,大约阅读时间需要 3 分钟。

下面的伪代码演示了如何对动态页面的结果进行缓存:

given a URL, try finding that page in the cache
if the page is in the cache:
return the cached page
else:
generate the page
save the generated page in the cache (for next time)
return the generated page

先简单写一个cache的使用例子,再根据例子分析下命令。(用cache前请先在setting中配置cache_backend,在文章最后有说明)

from django.core.cache import cache
def get_user_detail_info(user, refresh=False):    cache_key = '%s%s' % (user.id, user.name)    value = cache.get(cache_key)    if value and not refresh:        return value    else:        user_detail = USERDETAIL.objects.filter(user_id=user.id).all()        cache.set(cache_key, user_detail, 2*24*3600)        return user_detail
基本上就和上述的伪代码一样,先获取cache_key,然后用cache.get(
cache_key)获取信息,如果有值则直接返回。如果没有数值,则去数据中找,然后存入cache,返回。

django配置cache_backend

1)本机先上安装redis,具体安装不说了,一般就是一条命令brew,apt-get、yum等等

2)安装django-redis-cache,用于连接redis和django_cache

3)在django的settings.py中添加

CACHES = {    'default': {        'BACKEND': 'redis_cache.RedisCache',        'LOCATION': HOST+':6379',        'OPTIONS': {            'DB': 6,            'PARSER_CLASS': 'redis.connection.HiredisParser'        }    }}

转载地址:http://wovws.baihongyu.com/

你可能感兴趣的文章
RTImageAssets插件--@3x可自动生成@2x图片
查看>>
iOS开发的一些奇巧淫技
查看>>
常浏览的博客和网站
查看>>
Xcode 工程文件打开不出来, cannot be opened because the project file cannot be parsed.
查看>>
点击button实现Storyboard中TabBar Controller的tab切换
查看>>
Xcode 的正确打开方式——Debugging
查看>>
打包app出现的一个问题
查看>>
iOS在Xcode6中怎么创建OC category文件
查看>>
Expanding User-Defined Runtime Attributes in Xcode with Objective-C
查看>>
iOS7 UITabBar自定义选中图片显示为默认蓝色的Bug
查看>>
提升UITableView性能-复杂页面的优化
查看>>
25 iOS App Performance Tips & Tricks
查看>>
那些好用的iOS开发工具
查看>>
iOS最佳实践
查看>>
使用CFStringTransform将汉字转换为拼音
查看>>
更轻量的 View Controllers
查看>>
Chisel-LLDB命令插件,让调试更Easy
查看>>
时间格式化hh:mm:ss和HH:mm:ss区别
查看>>
Objective-C Autorelease Pool 的实现原理
查看>>
编程语言大牛王垠:编程的智慧,带你少走弯路
查看>>