core.cache ========== .. py:module:: core.cache .. autoapi-nested-parse:: This module implements a cache that can be used to serve entire requests or cache the output of any function (as long it's result can be stored in datastore). The intended use is to wrap functions that can be called from the outside (@exposed) with the @ResponseCache decorator. This will enable the cache provided in this module for that function, intercepting all calls to this function and serve a cached response instead of calling the function if possible. Authenticated users with "root" access can always bypass this cache by sending the X-Viur-Disable-Cache http Header along with their requests. Entities in this cache will expire if - Their TTL is exceeded - They're explicitly removed from the cache by calling :meth:`viur.core.cache.flushCache` using their path - A Datastore entity that has been accessed using db.get() from within the cached function has been modified - The wrapped function has run a query over a kind in which an entity has been added/edited/deleted ..Warning: As this cache is intended to be used with exposed functions, it will not only store the result of the wrapped function, but will also store and restore the Content-Type http header. This can cause unexpected behaviour if it's used to cache the result of non top-level functions, as calls to these functions now may cause this header to be rewritten. Attributes ---------- .. autoapisummary:: core.cache.CACHE_KINDNAME core.cache.DEFAULT_COMPRESSION core.cache.DEFAULT_SETTINGS Classes ------- .. autoapisummary:: core.cache.UserSensitive core.cache.BypassCache core.cache.ResponseCache Functions --------- .. autoapisummary:: core.cache.flushCache Module Contents --------------- .. py:data:: CACHE_KINDNAME :type: Final[str] :value: 'viur-cache' .. py:class:: UserSensitive Bases: :py:obj:`enum.IntEnum` Signals wherever the output of the wrapped method depends on the current user. Initialize self. See help(type(self)) for accurate signature. .. py:attribute:: IGNORE independent of wherever the user is a guest or known, all will get the same content. .. py:attribute:: GUEST_ONLY cache only for guests, no cache will be performed if the user is logged-in. .. py:attribute:: BOTH cache in two groups, one for guests and one for all users .. py:attribute:: INDIVIDUAL cache the result of that function for each individual users separately. .. py:class:: BypassCache Bases: :py:obj:`tuple` .. py:attribute:: reason .. py:data:: DEFAULT_COMPRESSION :value: -1 Default compression (alias for zlib.Z_DEFAULT_COMPRESSION) .. py:data:: DEFAULT_SETTINGS The global instance of DefaultSettings .. py:class:: ResponseCache(*, urls = None, renderer = sentinel, user_sensitive = sentinel, language_sensitive = sentinel, evaluated_args = sentinel, max_cache_time = sentinel, compression_level = sentinel) Bases: :py:obj:`Generic`\ [\ :py:obj:`Args`\ , :py:obj:`Value`\ ] Decorator class to cache the result of the reponse. ResponseCache caches: - Normal 200 responses, regardless of the content-type - Including headers changed by the wrapped function - Redirects 3** Parameters can control what and how long it should be cached, see the descriptions in :meth:`__init__`. Example usage: >>> from viur.core import exposed >>> import datetime >>> @exposed >>> @ResponseCache(max_cache_time=datetime.timedelta(days=1)) >>> def index(self): >>> return f"This result was cached at {datetime.datetime.now()}" Create a ResponseCache instance :param urls: A list of urls for this function, for which the cache should be enabled. A method can have several urls (e.g. /page/view, /pdf/page/view or /pdf/seite/view), and it might should not be cached under all urls (e.g. /vi/page/view). If the parameter is omitted, the URL is ignored for the check and the call is saved in the cache (unless excluded by other parameters), regardless of the path via which the method was called. :param renderer: This parameter can be used to specify render names (such as html, json) under which the result should be cached. The parameter can be used as an alternative to the `url` parameter, but can also be used in addition. :param user_sensitive: Signals wherever the output of the wrapped method depends on the current user. Look at :class:`UserSensitive` for parameter descriptions. :param language_sensitive: If True, signals that the output of the wrapped method should be cached separately for each language (because it's translated). :param evaluated_args: List of argument name having influence to the output generated by that wrapped method. This list *must* be complete! Parameters not named here are ignored! Warning: Double-check this list! F.e. if that function generates a list of entries and you miss the parameter "order" here, it would be impossible to sort the list. It would always have the ordering it had when the cache-entry was created. If the wrapped method use variable positional arguments (*args) or variable keyword arguments (**kwargs) you can include "arg" and/or "kwargs" to this list to accept all variable arguments that are passed by these. If only certain parameters of **kwargs should be considered add the key like it would be a explicit positional or keyword argument. :param max_cache_time: Specifies the maximum time an entry stays in the cache. Note: It's not erased from the database after that time, but it won't be served anymore. If None, the cache stays valid forever (until manually erased by calling flushCache). :param compression_level: Large pages may be too big for the datastore (max. approx. 1 MB, but including meta data). If this parameter is activated, the page is compressed before it is saved in the entity. Possible values for setting the compression level are the numbers 0 - 9. Compression is deactivated with None. See also :param:`DEFAULT_SETTINGS.raise_too_large`. .. py:attribute:: __slots__ :value: ('compression_level', 'evaluated_args', 'language_sensitive', 'max_cache_time', 'renderer',... .. py:attribute:: REDIRECT_FLAG :value: '<>' Flag used as content-type to signal that this is a cached redirect instead of a normal response. .. py:attribute:: urls :value: None .. py:attribute:: renderer :type: list[str | Type] | tuple[str | Type, Ellipsis] | None .. py:attribute:: user_sensitive :type: UserSensitive .. py:attribute:: language_sensitive :type: bool .. py:attribute:: evaluated_args :type: list[str] | tuple[str, Ellipsis] .. py:attribute:: compression_level :type: int | None .. py:method:: __call__(func) Does the actual work of wrapping a callable @exposed method and return a internal wrapper. .. py:method:: get_args(func, path, args, kwargs) Create a argument dict to build the cache key. In addition to the arguments to be considered (evaluated_args) of the request, parameters are also formed from the other options of this class. .. py:method:: get_string_from_args(args) Create a string key for the cache entity The parameters are sorted by key, and return as sha512 hash. :param args: The result of :meth:`get_args` .. py:method:: __repr__() Representation of this class .. py:function:: flushCache(prefix = None, key = None, kind = None) Flushes the cache. Its possible the flush only a part of the cache by specifying the path-prefix. The path is equal to the url that caused it to be cached (eg /page/view) and must be one listed in the 'url' param of :class:`ResponseCache`. :param prefix: Path or prefix that should be flushed. :param key: Flush all cache entries which may contain this key. Also flushes entries which executed a query over that kind. :param kind: Flush all cache entries which executed a query over that kind. Examples: - "/" would flush the main page (and only that), - "/*" everything from the cache, "/page/*" everything from the page-module (default render), - and "/page/view/*" only that specific subset of the page-module.