Django ----- several commonly used cache configuration

First, why use a cache?

We know that in Django, the request after reaching a view, the view will take data from the database into the template for dynamic rendering, the rendering result is that the user sees html page. However, if each request to fetch data from the database and rendering, will greatly reduce the performance of not only the server pressure, and the client can not get a response instantly. If the result of rendering can place faster cache, every time a request is over, whether or not a corresponding resource first checks the cache, if there is, return directly taken out from the cache in response, save the data fetch and rendered time, not only can greatly improve system performance, but also improve the user experience.

Cache is a type referred to, which typically is a fast memory medium, but may be other ways to speed up the data read

Second, the cache works:

1, no cache

  1. Django view from the DB data acquired by Models
  2. Then call the template to render, to form a real HttpResponse
  3. By Http Socket write data back to the client

2, there are cached

  1. The above is omitted 1,2
  2. The url taken directly from the cache storage pool had HttpResponse, returned to the client

Two, Django offers six ways cache

  1. Development and debugging cache
  2. Memory Cache
  3. Database Cache
  4. File caching (used)
  5. Memcache cache (using python-memcached module)
  6. Memcache cache (using pylibmc module)
  7. Use redis cache (common)
  8. Use mongdb Cache

Third, the common cache configuration

1, file cache

  1. Configuration

    CACHES = {
        'default': {
        # 指定缓存方式为文件
            'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
            # 指定缓存文件的路径
            'LOCATION': '路径',
            # 缓存超时时间(默认为300秒,None表示永不过期,0表示立即过期)
            # 可以在setting.py中单独配置CACHE_MIDDLEWARE_SECONDS = 10缓存超时时间,其优先级高于CACHES中的TIMEOUT。
            'TIMEOUT':300,                            
       }
    }   
    
  2. Explanation

    On linux system cache entry should be placed on the file system, as CACHE_BACKEND use the "file: //" cache type. For example, to cache data stored in / var / tmp / django_cache, use this setting:

    CACHE_BACKEND = 'file:///var/tmp/django_cache'
    

    ** Note: ** There are three slashes. The first two are file: //, and the third is the first character of the directory path, / var / tmp / django_cache.

    Using Windows, the file: // plus the letter after the file:

    file://d:/cache/django_cache
    
  3. Suitable scene

    Low-cost solution for smaller sites

2, Memcache cache (python-memcached)

  1. Install memcache

    1、安装memcache
    sudo apt-get install memcached
    2、运行memcached
    memcached -d -m 50 -p 11311 -u root
    -d重启或者启动服务 -m 最大内存 默认64 -p 端口号 - u 用户名
    3、默认只能本地访问需要修改
    
  2. Installation django python-memcached

    pip install python-memcached
    
  3. Individual configuration

    CACHES = {
     'default': {
      'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', # 指定缓存使用的引擎
      'LOCATION': '127.0.0.1:11211',   # 指定Memcache缓存服务器的IP地址和端口
      'OPTIONS':{
       'MAX_ENTRIES': 300,  
      }
     }
    }
    
  4. Multiple server configuration

    CACHES = {
     'default': {
      'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', # 指定缓存使用的引擎'LOCATION': [         
      # 指定一台或多台其他主机ip地址加端口为Memcache缓存服务器
        '127.0.0.1:11211',
        '127.0.0.1.3:11311',
        '127.0.0.1.4:11411',
    	]
    	# 或者也可以给缓存机器加权重,权重高的承担更多的请求
        # 'LOCATION': [
        #            ('172.19.26.240:11211',5),
        #            ('172.19.26.242:11211',1),
        #  ]
     }
    }
    
  5. Scenarios

    Caching mechanism for small sites, for example, you do a variety of blog, or access than smaller, meaning not great. Usually for mid-size or larger, Sheremetyevo.

3, Memcache cache (pylibmc)

4, redis cache

  1. Install redis

    pip install django_redis
    
  2. Create a database

    python manage.py createcachetable
    
  3. Configuration

    CACHES = {
        'default': {
            'BACKEND': 'django_redis.cache.RedisCache',
            # 缓存地址
            "LOCATION": "redis://127.0.0.1:6379",
             "OPTIONS": {
                 'MAX_ENTRIES': 2000
                 #使用线程池管理连接
                "CONNECTION_POOL_KWARGS": {"max_connections": 100}
            }
        },
    }
    
  4. Redis setting session information stored in django

    SESSION_ENGINE = "django.contrib.sessions.backends.cache"
    SESSION_CACHE_ALIAS = "default"
    

Fifth, the application cache

1. Description

Django offers different size of the cache can cache a page, you can cache only a portion of a page, or even can cache the entire site.

2, the use of the station

  1. Explanation

    Via intermediate user's request, through a series of authentication operations, if the requested content exists in the cache, using FetchFromCacheMiddleware obtain and return to the user,

    Before returned to the user, determines whether the cache already exists, if not, the cache will be saved to UpdateCacheMiddleware Django into cache, the cache in order to achieve the station,

  2. Configuration

    MIDDLEWARE = [
     'django.middleware.cache.UpdateCacheMiddleware',   # 响应HttpResponse中设置几个headers
      # 其它中间件
     'django.middleware.cache.FetchFromCacheMiddleware',   # 用来缓存通过GET和HEAD方法获取的状态码为200的响应
    ]
    
  3. Other configurations

    CACHE__MIDDLEWARE_SECONDS=15         # 设定超时时间为15秒
    
  4. note

    • UpdateCacheMiddleware must be placed at the beginning
    • FetchFromCacheMiddleware must be last
  5. Sample Code

    views view function

    from django.shortcuts import render
    import time
    
    def index(request):
     cache_time = time.time()
     return render(request,'index.html',{'time':cache_time})
    
    {% load cache %}    # 加载缓存
    <!DOCTYPE html>
    <html lang="en">
    <head>
         <meta charset="UTF-8">
         <title>缓存测试</title>
    </head>
    <body>
        <p>{{ time }}</p>
        {% cache 15  %}   # 设定超时时间为15秒
         <h3>{{ time }}</h3>
        {% endcache %}
    </body>
    </html>
    

3, separate views buffer

  1. A configuration

    from django.views.decorators.cache import cache_page
    @cache_page(60 * 10) 秒数,这里指缓存 10 分钟
    def cache_view(request):
      return render(request, 'cache/index.html', {'bar': bar})
    
  2. Second way configuration

    from django.views.decorators.cache import cache_page
    urlpatterns = [
    url(r'cache_test/$', cache_page(60 * 10)(cache_view)),
    ]
    

4, the cache topical use

  1. grammar

    1、引入TemplateTag
    {% load cache %}
    2、使用缓存
    {% cache 5000 缓存key %}
      缓存内容
    {% endcache %}
    
  2. template

    {% load cache %}    # 加载缓存
    <!DOCTYPE html>
    <html lang="en">
    <head>
     <meta charset="UTF-8">
     <title>缓存测试</title>
    </head>
    <body>
    <p>{{ time }}</p>
    {% cache 15 'cache_test' %}   # 设定超时时间为15秒
     <h3>{{ time }}</h3>
    {% endcache %}
    </body>
    </html>
    

Guess you like

Origin blog.csdn.net/qq_38953577/article/details/93595291