Debian Codegraph @

docs/quickstart.rst

raw
1 .. currentmodule:: flask_caching
2
3 Quickstart
4 ==========
5
6 Cache is managed through a ``Cache`` instance::
7
8 from flask import Flask
9 from flask_caching import Cache
10
11 config = {
12 "DEBUG": True, # some Flask specific configs
13 "CACHE_TYPE": "SimpleCache", # Flask-Caching related configs
14 "CACHE_DEFAULT_TIMEOUT": 300
15 }
16 app = Flask(__name__)
17 # tell Flask to use the above defined config
18 app.config.from_mapping(config)
19 cache = Cache(app)
20
21 The configuration can also be passed straight to the ``Cache`` instance,
22 without going through ``app.config``::
23
24 app = Flask(__name__)
25 cache = Cache(app, config={'CACHE_TYPE': 'SimpleCache'})
26
27 You may also set up your ``Cache`` instance later at configuration time using
28 **init_app** method::
29
30 cache = Cache(config={'CACHE_TYPE': 'SimpleCache'})
31
32 app = Flask(__name__)
33 cache.init_app(app)
34
35 You may also provide an alternate configuration dictionary, useful if there
36 will be multiple ``Cache`` instances each with a different backend::
37
38 #: Method A: During instantiation of class
39 cache = Cache(config={'CACHE_TYPE': 'SimpleCache'})
40 #: Method B: During init_app call
41 cache.init_app(app, config={'CACHE_TYPE': 'SimpleCache'})
42
43 .. versionadded:: 0.7
44 Multiple cache objects can be instantiated with different configuration
45 values.
46
47 .. warning::
48
49 ``CACHE_TYPE`` defaults to ``NullCache``, which does not cache anything.
50 A warning is emitted if it is left unset. Set ``CACHE_NO_NULL_WARNING``
51 to ``True`` to silence it. The available types/caching backends are listed under
52 :ref:`CACHE_TYPE <configuring-flask-caching>`.
53
54
55 Caching a View
56 --------------
57
58 With the cache set up, the :meth:`~Cache.cached` decorator caches the return
59 value of a view::
60
61 @app.route("/")
62 @cache.cached(timeout=50)
63 def index():
64 return "This response is cached for 50 seconds"
65
66
67 Caching Data
68 ------------
69
70 Values can also be stored and read back directly. The proxy methods need an
71 application context::
72
73 with app.app_context():
74 cache.set("answer", 42)
75 cache.get("answer") # 42
76
77
78 Next Steps
79 ----------
80
81 * :doc:`usage` covers view functions, memoization and template fragments.
82 * :doc:`configuration` describes the configuration
83 * :doc:`backends` describes the built-in cache backends.