diff --git a/site/zenodo_rdm/decorators.py b/site/zenodo_rdm/decorators.py new file mode 100644 index 00000000..a9bad1e8 --- /dev/null +++ b/site/zenodo_rdm/decorators.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2023 CERN. +# +# ZenodoRDM is free software; you can redistribute it and/or modify it +# under the terms of the MIT License; see LICENSE file for more details. +"""Decorators.""" + + +from functools import wraps + +from invenio_cache import current_cache +from flask import session +from flask_login import current_user + + +def has_flashes_or_authenticated_user(): + """Return True if there are pending flashes or user is authenticated.""" + return "_flashes" in session or current_user.is_authenticated + + +def cached_unless_authenticated_or_flashes(timeout=50, key_prefix="default"): + """Cache anonymous traffic.""" + def caching(f): + @wraps(f) + def wrapper(*args, **kwargs): + cache_fun = current_cache.cached( + timeout=timeout, key_prefix=key_prefix, + unless=has_flashes_or_authenticated_user) + return cache_fun(f)(*args, **kwargs) + return wrapper + return caching diff --git a/site/zenodo_rdm/views.py b/site/zenodo_rdm/views.py index a24c61fd..b11cdfb5 100644 --- a/site/zenodo_rdm/views.py +++ b/site/zenodo_rdm/views.py @@ -13,12 +13,14 @@ from invenio_records_resources.resources.records.utils import search_preference from marshmallow import ValidationError +from .decorators import cached_unless_authenticated_or_flashes from .support.support import ZenodoSupport # # Views # +@cached_unless_authenticated_or_flashes(timeout=600, key_prefix="frontpage") def frontpage_view_function(): """Zenodo frontpage view.""" recent_uploads = current_rdm_records.records_service.search(