Django note-Cache

Source: Internet
Author: User

1. Set Cache
The cache can be set to three levels: database, file, and memory.
You can modify the cache_backend variable in setting. py to set the cache.

2. Install memcached
There is no doubt that memory cache is the fastest cache. The installation steps are as follows:
1) install memcached Website: http://danga.com/memcached/
2) install memcached Python bindings. Two versions are available.
A) cmemcache: http://gijsbert.org/cmemcache.
B) Python-memcache: http://www.danga.com/memcached/
3) Configure cache_backednd
Configure the IP address and port of memcached. As shown in the following figure, memcached supports multi-server interconnection.
If multiple IP addresses are set, memcached considers these hosts as a whole.
Cache_backend = 'memcached: // 172.19.26.240: 11211; 172.19.26.242: 11212; 172.19.26.244: 11213 /'

Note: memcached disadvantages: because the memory cache is used, it will be lost when the server is down.

3. Database caching
1) create a cache Database
Python manage. py createcachetable [cache_table_name]
2) Configure cache_backend
Cache_backend = 'db: // cache_table_name'

Note: The backend of the database cache uses the same database specified by the settings file, and can only be the same. That is, if it is set to SQLite, the cache also uses it.

4. filesystem caching
1) set the cache directory
It must start with file. Example: If Linux is set to the/var/tmp/django_cache directory
Cache_backend = 'file: // var/tmp/django_cache
For Windows, specify the directory c:/Foo/bar.
File: // C:/Foo/Bar

Note: The specified directory must be readable and writable.

5. Local-memory caching
If you have no conditions to install memcached, local-memory is also a good choice.
It is simple and convenient, but the cache capability of this method is relatively weak. Setting method:
Cache_backend = 'locmem :///'

6. Dummy caching (for development)
This setting is used to develop a site with cache, but you do not want to implement it during development.
Setting method:
Cache_backend = 'dummy :///'

7. cache_backend parameter settings
Cache_backend can be used to set parameters such as timeout, maximum number of caches, and deletion ratio when the maximum number is reached. Example:

Cache_backend = 'memcached: // 127.0.0.1: 1121 /? Timeout = 30 & max_entries = 400 & cull_percentage = 2'
This value is set to time-out for 30 s and a maximum of 400. When the time-out period expires, 1/2 of content is deleted.

8. The per-site Cache
The simplest way is to cache the entire site. You only need to add the following middleware.
1) middleware_classes = {
'Django. Middleware. cache. updatecachemiddleware ',
'Django. Middleware. Common. commonmiddleware ',
'Django. Middleware. cache. fetchfromcachemiddleware ',
}
Note: Generally, classes are sorted by alphabetical. updatecachemiddleware must be set here.
At the top, see http://www.djangobook.com/en/2.0/chapter15/#order-of-middleware-classes
2) Add cache settings
A) cache_middleware_seconds-time unit of cache per page/s
B) if the cache is shared by multiple websites installed using the same Django,
Set this value to the current website name or a unique string that represents the Django instance to avoid key conflicts. If you don't care about it, you can set it to a null string.

Notes:
1) cache middleware caches each page without the get or post parameters, that is, if the user requests the page and passes the get or post parameters in the query string,
Middleware will not try to get cached pages. If you plan to use the whole site cache, remember this when designing your program. For example,
Do not use URLs with query strings unless those pages can not be cached.
2) You can only cache anonymous users and set cache_middleware_anonymous_only = true

9. The Per-View cache
1) define Per-View cache
Django. Views. decorators. cache defines a cache_page decoration, which can be used to cache view.
Example:
From Django. Views. decorators. cache import cache_page

Def my_view (request ):
#....
 
My_view = cache_page (my_view, 60*15)

Of course, you can also use the decorator Syntax of Python:
@ Cache_page (60*15)
Def my_view (request ):
#...
2) specify View cache through URL
1) This is obviously not a good method. If views are used without cache
Site, it cannot be reused. The recommended method is as follows:
From Django. Views. decorator. cache import cache_page

Urlpatterns = patterns ("",
(R' ^ Foo/(/d {1, 2})/$, cache_page (my_view, 60*15 )),
)

10. templage fragment caching
Example:
Export footemplate.html
{% Load cache %}
#.....
{% Cache 500 sidebar %}
... Sidebar...
{% Endcache %}

11. The low-level cache API
In many cases, you do not want to cache the entire page, or some views are not suitable for the entire cache. This will be used at this time
A low-level API provided by Django. It can cache all the stuff. Example:
From Django. Core. cache import Cache
Cache. Set ('My _ key', 'Hello, world! ', 30) # Set the cache variable my_key and cache for 30 s. If time is not set, the default value is set in setting.
Cache. Get ('My _ key', 'has expired') # retrieve the my_key variable of the cache. If it expires, return the has expired
Cache. Add ('add _ key', 'new value') # If add_key expires, the new value is set to new value. Otherwise, no value is added.

# Example of setting multiple interfaces:
Cache. Set ('A', 1)
Cache. Set ('B', 2)
Cache. get_many (['A', 'B']) returns a dictionary.
{'A': 1, 'B': 2}

11. More Cache
There are also many available cache-related resources. It is not described here.
<End>

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.