Django caching system

Cache

Django Dynamic Webbackground frame, generated in real time page accessed by the user, database operation several times, but multiple database access for the entire operating Websystem, will affect the efficiency, especially when traffic increases, the pressure on the database also We will keep rising.

With respect to the disk and memory operations, the cost of database access operations to pay much greater

First browser request, cachewill cache the entire contents of a single variable, or the like to the hard disk or the page memory, and set responsethe head

When a browser initiates a request again, will be compared with the cache expiration time, if the cache time is relatively new, it will re-request data and cached and then returned responseto the client, if the cache has not expired, then extracted directly from the cache data back to responsethe client

Cache-Control

HTTPProtocol header Cache-Control, Cache-Controlwith Expiresthe same effect, is to specify the duration of the current resources, control whether the browser cache fetch data directly from the browser or re-send the request to the server to take data. But Cache-Controlmore options, more detailed settings, if at the same time set, it takes precedence over theExpires

In pythonuse memcachedwe need additional installation memcachedas memcacheclient support

1
pip3 install python-memcached -i https://pypi.tuna.tsinghua.edu.cn/simple

Cache Settings

memcached

  • installationmemcached

    1
    2
    apt-get install memcached # debian
    yum install memcached # centos
  • Profiles:/etc/memcached.conf

    There are two configuration files may need to modify the parameters

    1
    2
    -m 64 #memcached memory size can be used by 
    -l 127.0 .0 .1 # listening IP address
  • On | Off memcachedService

    1
    2
    systemctl start memcached # open 
    systemctl stop memcached # close
  • Check the service status

    1
    systemctl status memcached

Configuration settings

Use memcachedthe cache, you first need the project settingsto configure the next file

1
2
3
4
5
6
7
8
= {CACHES 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', # specified engine used by the cache 'LOCATION': '172.16.19.26:11211', # specified cache server address, often the host address } }







View Cache

Can be cached for only some view function

Use django.views.decorators.cachedecorator in cache_pagea view function can be decorated

  • The code table model classes
1
2
class People(models.Model):
name = models.CharField(max_length=20,verbose_name='名字')
  • Code view function
1
2
3
4
5
6
7
django.views.decorators.cache from Import cache_page 

@cache_page (10) # cache 10 seconds
DEF index (Request):
Print ( 'view function is called')
SS = models.People.objects.all () return the render (Request, 'index.html', locals ())

  • Template page code
1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>展示数据</title>
</head>
<body>
{% for s in ss %}
<li>{{ s.name }} </li>
{% endfor %}
</body>
</html>

After the first refresh your browser,

Now add a new data object in the database

Then continue to refresh the browser, reads the front page will result cache, but does not display the newly added user

In addition to the cache is provided in view of the decorator function can also use the same function disposed decorator route matching section

The station's cache

The entire station is provided all the cache view, need to add the following section arranged end to end in the profile of the middleware

1
2
3
4
5
6
7
8
= MIDDLEWARE [ 'django.middleware.cache.UpdateCacheMiddleware', # header to add middleware # response will be cached 'django.middleware.security.SecurityMiddleware', ... 'django.middleware.cache.FetchFromCacheMiddleware', # tail to add middleware # cached response taken out ]







As well as with the global variable current site-wide cache valid time

1
= CACHE_MIDDLEWARE_SECONDS 10 # of seconds per page caching, default is 600

Local Cache

The main local cache to cache in the template page, select an area, when the user accesses the same page again, such as setting the unexpired cache, the cache does not regenerate local time rendering

1
2
3
4
5
{% Load cache%} 
local cache first need to load the cache tag {cache%% sec Key} {%}% endCache



Time template variables, for example, do a simple test, backstage view function every time visit, return to the current time

1
2
import time 
now = time.strftime('%H:%M:%S', time.localtime())

模板页面在使用时的代码

1
2
3
4
5
6
{% load cache %}

<p>这里是未缓存的时间:{{ now }}</p>
{% cache 10 time %}
<p>这里是缓存的时间:{{ now }}</p>
{% endcache %}

手动缓存

除了以上应用于各个业务中的缓存方式,还可以使用django所提供的cache接口进行缓存设置以及获取

  • 设置缓存
1
2
3
4
from django.core.cache import cache
#存储缓存数据
cache.set('cache_key',data,60*15)
#cache_key为存储在缓存中的唯一值,data为存储的数据,60*15为缓存有效时间
  • 获取缓存
1
2
3
#获取缓存数据
cache.get('cache_key','获取不到的默认值')
#cache_key为储存缓存数据的唯一值
  • 避免key值重复导致更新缓存,可以使用cache.add函数,基本用法与set相同
1
2
3
status = cache.add('add_key', 'New value')
# 当指定key值的缓存存在,add方法不会尝试更新缓存
# 返回值status为True时,代表存储成功,False代表存储失败
  • 清除缓存,通过cache.delete方法,该方法接收一个缓存key
1
cache.delete('cache_key')
  • 清空缓存,通过cache.clear方法,直接从缓存中清除所有
1
cache.clear()

注意

memcached不允许使用超过250个字符或包含空格或控制字符的缓存键值

使用这样的键值将会导致异常

Guess you like

Origin www.cnblogs.com/xgbky/p/11544521.html