| 1 |
""" |
| 2 |
flask_caching.backends.uwsgicache |
| 3 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 4 |
|
| 5 |
The uWSGI caching backend. |
| 6 |
|
| 7 |
:copyright: (c) 2018 by Peter Justin. |
| 8 |
:copyright: (c) 2010 by Thadeus Burgess. |
| 9 |
:license: BSD, see LICENSE for more details. |
| 10 |
""" |
| 11 |
|
| 12 |
from cachelib import UWSGICache as CachelibUWSGICache |
| 13 |
|
| 14 |
from flask_caching.backends.base import BaseCache |
| 15 |
|
| 16 |
|
| 17 |
class UWSGICache(BaseCache, CachelibUWSGICache): |
| 18 |
"""Implements the cache using uWSGI's caching framework. |
| 19 |
|
| 20 |
.. note:: |
| 21 |
This class cannot be used when running under PyPy, because the uWSGI |
| 22 |
API implementation for PyPy is lacking the needed functionality. |
| 23 |
|
| 24 |
:param default_timeout: The default timeout in seconds. |
| 25 |
:param cache: The name of the caching instance to connect to, for |
| 26 |
example: mycache@localhost:3031, defaults to an empty string, which |
| 27 |
means uWSGI will use the first cache instance initialized. |
| 28 |
If the cache is in the same instance as the werkzeug app, |
| 29 |
you only have to provide the name of the cache. |
| 30 |
""" |
| 31 |
|
| 32 |
def __init__(self, default_timeout=300, cache=""): |
| 33 |
BaseCache.__init__(self, default_timeout=default_timeout) |
| 34 |
CachelibUWSGICache.__init__( |
| 35 |
self, |
| 36 |
cache=cache, |
| 37 |
default_timeout=default_timeout, |
| 38 |
) |
| 39 |
|
| 40 |
try: |
| 41 |
import uwsgi |
| 42 |
|
| 43 |
self._uwsgi = uwsgi |
| 44 |
except ImportError as e: |
| 45 |
raise RuntimeError( |
| 46 |
"uWSGI could not be imported, are you running under uWSGI?" |
| 47 |
) from e |
| 48 |
|
| 49 |
if "cache2" not in uwsgi.opt: |
| 50 |
raise RuntimeError( |
| 51 |
"You must enable cache2 in uWSGI configuration: " |
| 52 |
"https://uwsgi-docs.readthedocs.io/en/latest/Caching.html" |
| 53 |
) |
| 54 |
|
| 55 |
@classmethod |
| 56 |
def factory(cls, app, config, args, kwargs): |
| 57 |
# The name of the caching instance to connect to, for |
| 58 |
# example: mycache@localhost:3031, defaults to an empty string, which |
| 59 |
# means uWSGI will cache in the local instance. If the cache is in the |
| 60 |
# same instance as the werkzeug app, you only have to provide the name |
| 61 |
# of the cache. |
| 62 |
uwsgi_cache_name = config.get("CACHE_UWSGI_NAME", "") |
| 63 |
kwargs.update(dict(cache=uwsgi_cache_name)) |
| 64 |
return cls(*args, **kwargs) |