django缓存优化 基于Redis缓存项目实例

安装缓存后端

pip install django-redis-cache

配置django缓存为redis

CACHES = {
    'default': {
        'BACKEND': 'redis_cache.cache.RedisCache',
        'LOCATION': '127.0.0.1:6379',
        "OPTIONS": {
            "CLIENT_CLASS": "redis_cache.client.DefaultClient",
        },
        'KEY_PREFIX':'kakaRedisTest',
        'TIMEOUT':480,
    },
}

配置url

from django.conf.urls import url
from django.contrib import admin
from blog.views import * #new
from django.views.decorators.cache import cache_page #new
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', index, name='index'),
    url(r'^index2/$', cache_page(3)(Index2.as_view()), name='index2'),
]

视图函数

from django.shortcuts import render
from django.views.generic import TemplateView #new
from datetime import datetime #new
from django.core.cache import cache #new
#from django.views.decorators.cache import cache_page
# Create your views here.
def index(request):
    dt = datetime.now().second
    key = 'titles'
    titles_cached = cache.get(key)
    if not titles_cached:
        titles = [(dt, 'kylie'), (dt,'coco'), (dt, 'camel')]
        cache.set(key,titles)
    else:
        titles = titles_cached
    context = {'dt':dt, 'titles':titles}
    return render(request, 'index.html', context)


class Index2(TemplateView):
    template_name = 'index2.html'
    def get_context_data(self, **kwargs):
        dt = datetime.now().second
        return {'dt': dt}

模板index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% load cache %}
{% cache 3 titleCache %}
    <h1>cached seconds:{{ dt }}</h1>
{% endcache %}
    <h1>seconds:{{ dt }}</h1>
<ul>
    {% for title in titles %}
        <li>{{ title.0}},{{ title.1 }}</li>
    {% endfor %}

</ul>

</body>
</html>

index2.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>seconds:{{ dt }}</h1>
</body>
</html>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值