zoukankan      html  css  js  c++  java
  • cache

    Django 官方关于cache的介绍:https://docs.djangoproject.com/en/dev/topics/cache/

    Django 是动态网站,一般来说需要实时地生成访问的网页,展示给访问者,这样,内容可以随时变化,但是从数据库读多次把所需要的数据取出来,要比从内存或者硬盘等一次读出来 付出的成本大很多。

    缓存系统工作原理:

    对于给定的网址,尝试从缓存中找到网址,如果页面在缓存中,直接返回缓存的页面,如果缓存中没有,一系列操作(比如查数据库)后,保存生成的页面内容到缓存系统以供下一次使用,然后返回生成的页面内容。

    一 配置

    # Django settings 中 cache 默认为
     
    { 'default': {
            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        }
    }
     
     
    # 也就是默认利用本地的内存来当缓存,速度很快。当然可能出来内存不够用的情况,其它的一些内建可用的 Backends 有
     
    'django.core.cache.backends.locmem.LocMemCache'
    'django.core.cache.backends.dummy.DummyCache'
    'django.core.cache.backends.db.DatabaseCache'
    'django.core.cache.backends.filebased.FileBasedCache'
    'django.core.cache.backends.memcached.MemcachedCache'
    'django.core.cache.backends.memcached.PyLibMCCache'
    View Code

    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
    View Code

    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
            }
        }
    }
    View Code

    FileBasedCache

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

    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',
                ]
            }
        }
    View Code

    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',
                ]
            }
        }
    View Code

    二 应用  

    1 全站使用

    使用中间件,经过一系列的认证等操作,如果内容在缓存中存在,则使用FetchFromCacheMiddleware获取内容并返回给用户,当返回给用户之前,判断缓存中是否已经存在,如果不存在则UpdateCacheMiddleware会将缓存保存至缓存,从而实现全站缓存
    
        MIDDLEWARE = [
            'django.middleware.cache.UpdateCacheMiddleware',
            # 其他中间件...
            'django.middleware.cache.FetchFromCacheMiddleware',
        ]
    
        CACHE_MIDDLEWARE_ALIAS = ""
        CACHE_MIDDLEWARE_SECONDS = ""
        CACHE_MIDDLEWARE_KEY_PREFIX = ""
    View Code

    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)),
            ]
    View Code

    3 模版局部视图使用

    1. 引入TemplateTag
    
            {% load cache %}
    
       2. 使用缓存
    
            {% cache 5000 缓存key %}
                缓存内容
            {% endcache %}
    View Code
    # 一般来说我们用 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 可用的最快的缓存
    实例演示
  • 相关阅读:
    OO第三次阶段性总结
    OO第二次阶段性总结
    OO第一次阶段性总结
    【软工】提问回顾与个人总结
    【软工】结对编程作业
    【软工】第一次阅读作业
    【软工】第0次个人作业
    oo作业总结(四)
    OO作业总结(三)
    oo作业总结(二)
  • 原文地址:https://www.cnblogs.com/navysummer/p/8455025.html
Copyright © 2011-2022 走看看