| 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 typing import Any |
| 13 |
|
| 14 |
from cachelib import UWSGICache as CachelibUWSGICache |
| 15 |
from flask import Flask |
| 16 |
|
| 17 |
from flask_caching.backends.base import BaseCache |
| 18 |
|
| 19 |
|
| 20 |
class UWSGICache(BaseCache, CachelibUWSGICache): |
| 21 |
"""Implements the cache using uWSGI's caching framework. |
| 22 |
|
| 23 |
.. note:: |
| 24 |
This class cannot be used when running under PyPy, because the uWSGI |
| 25 |
API implementation for PyPy is lacking the needed functionality. |
| 26 |
|
| 27 |
:param default_timeout: The default timeout in seconds. |
| 28 |
:param cache: The name of the caching instance to connect to, for |
| 29 |
example: mycache@localhost:3031, defaults to an empty string, which |
| 30 |
means uWSGI will use the first cache instance initialized. |
| 31 |
If the cache is in the same instance as the werkzeug app, |
| 32 |
you only have to provide the name of the cache. |
| 33 |
:param ignore_delete_many_errors: If set to ``False`` the ``delete_many`` |
| 34 |
method raises a ``RuntimeError`` in case |
| 35 |
a key couldn't be deleted. |
| 36 |
Defaults to ``False``. |
| 37 |
""" |
| 38 |
|
| 39 |
def __init__( |
| 40 |
self, |
| 41 |
default_timeout: int = 300, |
| 42 |
cache: str = "", |
| 43 |
ignore_delete_many_errors: bool = False, |
| 44 |
) -> None: |
| 45 |
CachelibUWSGICache.__init__( |
| 46 |
self, |
| 47 |
cache=cache, |
| 48 |
default_timeout=default_timeout, |
| 49 |
ignore_delete_many_errors=ignore_delete_many_errors, |
| 50 |
) |
| 51 |
|
| 52 |
try: |
| 53 |
import uwsgi |
| 54 |
|
| 55 |
self._uwsgi = uwsgi |
| 56 |
except ImportError as e: |
| 57 |
raise RuntimeError( |
| 58 |
"uWSGI could not be imported, are you running under uWSGI?" |
| 59 |
) from e |
| 60 |
|
| 61 |
if "cache2" not in uwsgi.opt: |
| 62 |
raise RuntimeError( |
| 63 |
"You must enable cache2 in uWSGI configuration: " |
| 64 |
"https://uwsgi-docs.readthedocs.io/en/latest/Caching.html" |
| 65 |
) |
| 66 |
|
| 67 |
@classmethod |
| 68 |
def factory( |
| 69 |
cls, |
| 70 |
app: Flask, |
| 71 |
config: dict[str, Any], |
| 72 |
args: list[Any], |
| 73 |
kwargs: dict[str, Any], |
| 74 |
) -> "UWSGICache": |
| 75 |
# The name of the caching instance to connect to, for |
| 76 |
# example: mycache@localhost:3031, defaults to an empty string, which |
| 77 |
# means uWSGI will cache in the local instance. If the cache is in the |
| 78 |
# same instance as the werkzeug app, you only have to provide the name |
| 79 |
# of the cache. |
| 80 |
uwsgi_cache_name = config.get("CACHE_UWSGI_NAME", "") |
| 81 |
kwargs.update(dict(cache=uwsgi_cache_name)) |
| 82 |
return cls(*args, **kwargs) |