Skip to content
Myr

caching.rst

This file

Path

docs/patterns/caching.rst

69 lines · 2.5 KiB

Last changed by

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

History of this file

Take it

1.. _caching-pattern:23Caching4=======56When your application runs slow, throw some caches in.  Well, at least7it's the easiest way to speed up things.  What does a cache do?  Say you8have a function that takes some time to complete but the results would9still be good enough if they were 5 minutes old.  So then the idea is that10you actually put the result of that calculation into a cache for some11time.1213Flask itself does not provide caching for you, but Werkzeug, one of the14libraries it is based on, has some very basic cache support.  It supports15multiple cache backends, normally you want to use a memcached server.1617Setting up a Cache18------------------1920You create a cache object once and keep it around, similar to how21:class:`~flask.Flask` objects are created.  If you are using the22development server you can create a23:class:`~werkzeug.contrib.cache.SimpleCache` object, that one is a simple24cache that keeps the item stored in the memory of the Python interpreter::2526    from werkzeug.contrib.cache import SimpleCache27    cache = SimpleCache()2829If you want to use memcached, make sure to have one of the memcache modules30supported (you get them from `PyPI <https://pypi.python.org/pypi>`_) and a31memcached server running somewhere.  This is how you connect to such an32memcached server then::3334    from werkzeug.contrib.cache import MemcachedCache35    cache = MemcachedCache(['127.0.0.1:11211'])3637If you are using App Engine, you can connect to the App Engine memcache38server easily::3940    from werkzeug.contrib.cache import GAEMemcachedCache41    cache = GAEMemcachedCache()4243Using a Cache44-------------4546Now how can one use such a cache?  There are two very important47operations: :meth:`~werkzeug.contrib.cache.BaseCache.get` and48:meth:`~werkzeug.contrib.cache.BaseCache.set`.  This is how to use them:4950To get an item from the cache call51:meth:`~werkzeug.contrib.cache.BaseCache.get` with a string as key name.52If something is in the cache, it is returned.  Otherwise that function53will return ``None``::5455    rv = cache.get('my-item')5657To add items to the cache, use the :meth:`~werkzeug.contrib.cache.BaseCache.set`58method instead.  The first argument is the key and the second the value59that should be set.  Also a timeout can be provided after which the cache60will automatically remove item.6162Here a full example how this looks like normally::6364    def get_my_item():65        rv = cache.get('my-item')66        if rv is None:67            rv = calculate_value()68            cache.set('my-item', rv, timeout=5 * 60)69        return rv