码迷,mamicode.com
首页 > 其他好文 > 详细

缓存系统 | Django自带 | Django开发

时间:2017-10-29 12:51:26      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:ref   unix   sel   pytho   结果   url   prefix   重复   直接   

-- 缓存
    # 减少重复消耗计算资源;
    # Django自带一个健壮的缓存系统来保存动态页面;
    1.设置缓存
        -- 设置数据缓存地址:1.数据库;2.文件系统;
        -- settings.py中的CACHES配置:
            # 参数TIMEOUT:缓存过期时间;
            # 默认300秒;
            # 下面是对存到本地的配置:
            # None表示永久,0表示立即失效;
            # CACHES={
            #     ‘default‘: {
            #         ‘BACKEND‘: ‘django.core.cache.backends.locmem.LocMemCache‘,
            #         ‘TIMEOUT‘: 60,
            #     }
            # }
        -- 将缓存保存到redis中
            # 默认使用其中的数据库1;
            # 安装包:pip install django-redis-cache
            # CACHES = {
            #     "default": {
            #         "BACKEND": "redis_cache.cache.RedisCache",
            #         "LOCATION": "localhost:6379",
            #         ‘TIMEOUT‘: 60,
            #     },
            # }
        -- 连接redis查看存的数据
            # 连接:redis-cli
            # 切换数据库:select 1
            # 查看键:keys *
            # 查看值:get 键
    2.单个view缓存
        2.1 缓存一个视图函数
            -- 导入一个模块
                from django.views.decorators.cache import cache_page
            -- 在视图函数上加上一个装饰器
                @cache_page(60 * 15)
                # 装饰器中传入的timeout参数指的是时间;
                def index(request):
                    return HttpResponse(hello1)
                # 附:视图缓存与URL无关,如果多个URL指向同一视图,每个URL将会分别缓存

    3.模板片段缓存
        -- 使用cache模板标签来缓存模板的一个片段
        -- 需要两个参数:
            # 缓存时间,以秒为单位
            # 给缓存片段起的名称
            # {% load cache %}
            # {% cache 500 hello %}
            # hello1
            # <!--hello2-->
            # {% endcache %}
    4.底层的缓存API
        from django.core.cache import cache

        # 设置:cache.set(键,值,有效时间)
        # 获取:cache.get(键)
        # 删除:cache.delete(键)
        # 清空:cache.clear()

 ------------------------------------------------------------------>>>>>>>>>>  其他缓存引擎配置

1.DummyCache

# 此为开始调试用,实际内部不做任何操作
    # 配置:
        CACHES = {
            default: {
                BACKEND: django.core.cache.backends.dummy.DummyCache,     # 引擎
                TIMEOUT: 300,                                               # 缓存超时时间(默认300,None表示永不过期,0表示立即过期)
                OPTIONS:{
                    MAX_ENTRIES: 300,                                       # 最大缓存个数(默认300)
                    CULL_FREQUENCY: 3,                                      # 缓存到达最大个数之后,剔除缓存个数的比例,即:1/CULL_FREQUENCY(默认3)
                },
                KEY_PREFIX: ‘‘,                                             # 缓存key的前缀(默认空)
                VERSION: 1,                                                 # 缓存key的版本(默认1)
                KEY_FUNCTION 函数名                                          # 生成key的函数(默认函数会生成为:【前缀:版本:key】)
            }
        }


    # 自定义key
    def default_key_func(key, key_prefix, version):
        """
        Default function to generate keys.

        Constructs the key used by all other methods. By default it prepends
        the `key_prefix‘. KEY_FUNCTION can be used to specify an alternate
        function with custom key making behavior.
        """
        return %s:%s:%s % (key_prefix, version, key)

    def get_key_func(key_func):
        """
        Function to decide which key function to use.

        Defaults to ``default_key_func``.
        """
        if key_func is not None:
            if callable(key_func):
                return key_func
            else:
                return import_string(key_func)
        return default_key_func

2.DatabaseCache

# 利用数据库来缓存,利用命令创建相应的表:python manage.py createcachetable cache_table_name

CACHES = {
    default: {
        BACKEND: django.core.cache.backends.db.DatabaseCache,
        LOCATION: cache_table_name,
        TIMEOUT: 600,
        OPTIONS: {
            MAX_ENTRIES: 2000
        }
    }
}

3.FileBasedCache

# 利用文件系统来缓存:
CACHES = {
    default: {
        BACKEND: django.core.cache.backends.filebased.FileBasedCache,
        LOCATION: /var/tmp/django_cache,
        TIMEOUT: 600,
        OPTIONS: {
            MAX_ENTRIES: 1000
        }
    }
}

4.MemcachedCache

# 此缓存使用python-memcached模块连接memcache

    CACHES = {
        default: {
            BACKEND: django.core.cache.backends.memcached.MemcachedCache,
            LOCATION: 127.0.0.1:11211,
        }
    }

    CACHES = {
        default: {
            BACKEND: django.core.cache.backends.memcached.MemcachedCache,
            LOCATION: unix:/tmp/memcached.sock,
        }
    }   

    CACHES = {
        default: {
            BACKEND: django.core.cache.backends.memcached.MemcachedCache,
            LOCATION: [
                172.19.26.240:11211,
                172.19.26.242:11211,
            ]
        }
    }

5.PyLibMCCache

# 此缓存使用pylibmc模块连接memcache
    
    CACHES = {
        default: {
            BACKEND: django.core.cache.backends.memcached.PyLibMCCache,
            LOCATION: 127.0.0.1:11211,
        }
    }

    CACHES = {
        default: {
            BACKEND: django.core.cache.backends.memcached.PyLibMCCache,
            LOCATION: /tmp/memcached.sock,
        }
    }   

    CACHES = {
        default: {
            BACKEND: django.core.cache.backends.memcached.PyLibMCCache,
            LOCATION: [
                172.19.26.240:11211,
                172.19.26.242:11211,
            ]
        }
    }

==========================================》》》》》》使用

1.全站使用

使用中间件,经过一系列的认证等操作,如果内容在缓存中存在,则使用FetchFromCacheMiddleware获取内容并返回给用户,当返回给用户之前,判断缓存中是否已经存在,如果不存在则UpdateCacheMiddleware会将缓存保存至缓存,从而实现全站缓存

    MIDDLEWARE = [
        django.middleware.cache.UpdateCacheMiddleware,
        # 其他中间件...
        django.middleware.cache.FetchFromCacheMiddleware,
    ]

    CACHE_MIDDLEWARE_ALIAS = ""
    CACHE_MIDDLEWARE_SECONDS = ""
    CACHE_MIDDLEWARE_KEY_PREFIX = ""

2.单独视图缓存

方式一:
        from django.views.decorators.cache import cache_page

        @cache_page(60 * 15)
        def my_view(request):
            ...

    方式二:
        from django.views.decorators.cache import cache_page

        urlpatterns = [
            url(r^foo/([0-9]{1,2})/$, cache_page(60 * 15)(my_view)),
        ]

3.模板局部视图使用

1. 引入TemplateTag

        {% load cache %}

   2. 使用缓存

        {% cache 5000 缓存key %}
            缓存内容
        {% endcache %}

4.实例演示

# 一般来说我们用 Django 来搭建一个网站,要用到数据库等。

from django.shortcuts import render
def index(request):
    # 读取数据库等 并渲染到网页
    # 数据库获取的结果保存到 queryset 中
    return render(request, index.html, {queryset:queryset})
# 像这样每次访问都要读取数据库,一般的小网站没什么问题,当访问量非常大的时候,就会有很多次的数据库查询,肯定会造成访问速度变慢,服务器资源占用较多等问题。

#------------------------------------------
#------------------------------------------

from django.shortcuts import render
from django.views.decorators.cache import cache_page
 
@cache_page(60 * 15) # 秒数,这里指缓存 15 分钟,不直接写900是为了提高可读性
def index(request):
    # 读取数据库等 并渲染到网页
    return render(request, index.html, {queryset:queryset})
# 当使用了cache后,访问情况变成了如下:


# 访问一个网址时, 尝试从 cache 中找有没有缓存内容
# 如果网页在缓存中显示缓存内容,否则生成访问的页面,保存在缓存中以便下次使用,显示缓存的页面。
# 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
# Memcached 是目前 Django 可用的最快的缓存

 

缓存系统 | Django自带 | Django开发

标签:ref   unix   sel   pytho   结果   url   prefix   重复   直接   

原文地址:http://www.cnblogs.com/pymkl/p/7749499.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!