Cache
最后更新于:2022-04-01 04:08:02
# Cache
The main problem with dynamic Web sites is, well, they're dynamic. Eachtime a user requests a page, the webserver executes a lot of code, queriesthe database, renders templates until the visitor gets the page he sees.
This is a lot more expensive than just loading a file from the file systemand sending it to the visitor.
For most Web applications, this overhead isn't a big deal but once itbecomes, you will be glad to have a cache system in place.
### How Caching Works
Caching is pretty simple. Basically you have a cache object lurking aroundsomewhere that is connected to a remote cache or the file system orsomething else. When the request comes in you check if the current pageis already in the cache and if so, you're returning it from the cache.Otherwise you generate the page and put it into the cache. (Or a fragmentof the page, you don't have to cache the full thing)
Here is a simple example of how to cache a sidebar for a template:
~~~
def get_sidebar(user):
identifier = 'sidebar_for/user%d' % user.id
value = cache.get(identifier)
if value is not None:
return value
value = generate_sidebar_for(user=user)
cache.set(identifier, value, timeout=60 * 5)
return value
~~~
### Creating a Cache Object
To create a cache object you just import the cache system of your choicefrom the cache module and instantiate it. Then you can start workingwith that object:
~~~
>>> from werkzeug.contrib.cache import SimpleCache
>>> c = SimpleCache()
>>> c.set("foo", "value")
>>> c.get("foo")
'value'
>>> c.get("missing") is None
True
~~~
Please keep in mind that you have to create the cache and put it somewhereyou have access to it (either as a module global you can import or you justput it into your WSGI application).
### Cache System API
*class *werkzeug.contrib.cache.BaseCache(*default_timeout=300*)
Baseclass for the cache systems. All the cache systems implement thisAPI or a superset of it.
| 参数: | **default_timeout** – the default timeout that is used if no timeout isspecified on [set()](# "werkzeug.contrib.cache.BaseCache.set"). |
|-----|-----|
add(*key*, *value*, *timeout=None*)
Works like [set()](# "werkzeug.contrib.cache.BaseCache.set") but does not overwrite the values of alreadyexisting keys.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple"><li><strong>key</strong> – the key to set</li><li><strong>value</strong> – the value for the key</li><li><strong>timeout</strong> – the cache timeout for the key or the defaulttimeout if not specified.</li></ul></td></tr></tbody></table>
clear()
Clears the cache. Keep in mind that not all caches supportcompletely clearing the cache.
dec(*key*, *delta=1*)
Decrements the value of a key by delta. If the key doesnot yet exist it is initialized with -delta.
For supporting caches this is an atomic operation.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple"><li><strong>key</strong> – the key to increment.</li><li><strong>delta</strong> – the delta to subtract.</li></ul></td></tr></tbody></table>
delete(*key*)
Deletes key from the cache. If it does not exist in the cachenothing happens.
| 参数: | **key** – the key to delete. |
|-----|-----|
delete_many(**keys*)
Deletes multiple keys at once.
| 参数: | **keys** – The function accepts multiple keys as positionalarguments. |
|-----|-----|
get(*key*)
Looks up key in the cache and returns the value for it.If the key does not exist None is returned instead.
| 参数: | **key** – the key to be looked up. |
|-----|-----|
get_dict(**keys*)
Works like [get_many()](# "werkzeug.contrib.cache.BaseCache.get_many") but returns a dict:
~~~
d = cache.get_dict("foo", "bar")
foo = d["foo"]
bar = d["bar"]
~~~
| 参数: | **keys** – The function accepts multiple keys as positionalarguments. |
|-----|-----|
get_many(**keys*)
Returns a list of values for the given keys.For each key a item in the list is created. Example:
~~~
foo, bar = cache.get_many("foo", "bar")
~~~
If a key can't be looked up None is returned for that keyinstead.
| 参数: | **keys** – The function accepts multiple keys as positionalarguments. |
|-----|-----|
inc(*key*, *delta=1*)
Increments the value of a key by delta. If the key doesnot yet exist it is initialized with delta.
For supporting caches this is an atomic operation.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple"><li><strong>key</strong> – the key to increment.</li><li><strong>delta</strong> – the delta to add.</li></ul></td></tr></tbody></table>
set(*key*, *value*, *timeout=None*)
Adds a new key/value to the cache (overwrites value, if key alreadyexists in the cache).
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple"><li><strong>key</strong> – the key to set</li><li><strong>value</strong> – the value for the key</li><li><strong>timeout</strong> – the cache timeout for the key (if not specified,it uses the default timeout).</li></ul></td></tr></tbody></table>
set_many(*mapping*, *timeout=None*)
Sets multiple keys and values from a mapping.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple"><li><strong>mapping</strong> – a mapping with the keys/values to set.</li><li><strong>timeout</strong> – the cache timeout for the key (if not specified,it uses the default timeout).</li></ul></td></tr></tbody></table>
### Cache Systems
*class *werkzeug.contrib.cache.NullCache(*default_timeout=300*)
A cache that doesn't cache. This can be useful for unit testing.
| 参数: | **default_timeout** – a dummy parameter that is ignored but existsfor API compatibility with other caches. |
|-----|-----|
*class *werkzeug.contrib.cache.SimpleCache(*threshold=500*, *default_timeout=300*)
Simple memory cache for single process environments. This class existsmainly for the development server and is not 100% thread safe. It triesto use as many atomic operations as possible and no locks for simplicitybut it could happen under heavy load that keys are added multiple times.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple"><li><strong>threshold</strong> – the maximum number of items the cache stores beforeit starts deleting some.</li><li><strong>default_timeout</strong> – the default timeout that is used if no timeout isspecified on <a class="reference internal" href="#werkzeug.contrib.cache.BaseCache.set" title="werkzeug.contrib.cache.BaseCache.set"><tt class="xref py py-meth docutils literal"><span class="pre">set()</span></tt></a>.</li></ul></td></tr></tbody></table>
*class *werkzeug.contrib.cache.MemcachedCache(*servers=None*, *default_timeout=300*, *key_prefix=None*)
A cache that uses memcached as backend.
The first argument can either be an object that resembles the API of amemcache.Client or a tuple/list of server addresses. In theevent that a tuple/list is passed, Werkzeug tries to import the bestavailable memcache library.
Implementation notes: This cache backend works around some limitations inmemcached to simplify the interface. For example unicode keys are encodedto utf-8 on the fly. Methods such as [get_dict()](# "werkzeug.contrib.cache.BaseCache.get_dict") returnthe keys in the same format as passed. Furthermore all get methodssilently ignore key errors to not cause problems when untrusted user datais passed to the get methods which is often the case in web applications.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple"><li><strong>servers</strong> – a list or tuple of server addresses or alternativelya <tt class="xref py py-class docutils literal"><span class="pre">memcache.Client</span></tt> or a compatible client.</li><li><strong>default_timeout</strong> – the default timeout that is used if no timeout isspecified on <a class="reference internal" href="#werkzeug.contrib.cache.BaseCache.set" title="werkzeug.contrib.cache.BaseCache.set"><tt class="xref py py-meth docutils literal"><span class="pre">set()</span></tt></a>.</li><li><strong>key_prefix</strong> – a prefix that is added before all keys. This makes itpossible to use the same memcached server for differentapplications. Keep in mind that<a class="reference internal" href="#werkzeug.contrib.cache.BaseCache.clear" title="werkzeug.contrib.cache.BaseCache.clear"><tt class="xref py py-meth docutils literal"><span class="pre">clear()</span></tt></a> will also clear keys with adifferent prefix.</li></ul></td></tr></tbody></table>
*class *werkzeug.contrib.cache.GAEMemcachedCache
This class is deprecated in favour of [MemcachedCache](# "werkzeug.contrib.cache.MemcachedCache") whichnow supports Google Appengine as well.
在 0.8 版更改: Deprecated in favour of [MemcachedCache](# "werkzeug.contrib.cache.MemcachedCache").
*class *werkzeug.contrib.cache.RedisCache(*host='localhost'*, *port=6379*, *password=None*, *db=0*, *default_timeout=300*, *key_prefix=None*)
Uses the Redis key-value store as a cache backend.
The first argument can be either a string denoting address of the Redisserver or an object resembling an instance of a redis.Redis class.
Note: Python Redis API already takes care of encoding unicode strings onthe fly.
0.7 新版功能.
0.8 新版功能: key_prefix was added.
在 0.8 版更改: This cache backend now properly serializes objects.
在 0.8.3 版更改: This cache backend now supports password authentication.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple"><li><strong>host</strong> – address of the Redis server or an object which API iscompatible with the official Python Redis client (redis-py).</li><li><strong>port</strong> – port number on which Redis server listens for connections.</li><li><strong>password</strong> – password authentication for the Redis server.</li><li><strong>db</strong> – db (zero-based numeric index) on Redis Server to connect.</li><li><strong>default_timeout</strong> – the default timeout that is used if no timeout isspecified on <a class="reference internal" href="#werkzeug.contrib.cache.BaseCache.set" title="werkzeug.contrib.cache.BaseCache.set"><tt class="xref py py-meth docutils literal"><span class="pre">set()</span></tt></a>.</li><li><strong>key_prefix</strong> – A prefix that should be added to all keys.</li></ul></td></tr></tbody></table>
*class *werkzeug.contrib.cache.FileSystemCache(*cache_dir*, *threshold=500*, *default_timeout=300*, *mode=384*)
A cache that stores the items on the file system. This cache dependson being the only user of the cache_dir. Make absolutely sure thatnobody but this cache stores files there or otherwise the cache willrandomly delete files therein.
<table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple"><li><strong>cache_dir</strong> – the directory where cache files are stored.</li><li><strong>threshold</strong> – the maximum number of items the cache stores beforeit starts deleting some.</li><li><strong>default_timeout</strong> – the default timeout that is used if no timeout isspecified on <a class="reference internal" href="#werkzeug.contrib.cache.BaseCache.set" title="werkzeug.contrib.cache.BaseCache.set"><tt class="xref py py-meth docutils literal"><span class="pre">set()</span></tt></a>.</li><li><strong>mode</strong> – the file mode wanted for the cache files, default 0600</li></ul></td></tr></tbody></table>