Coverage for seedboxsync/front/cache.py: 86%

14 statements  

« prev     ^ index     » next       coverage.py v7.16.1, created at 2026-09-26 17:14 +0000

1# 

2# Copyright (C) 2015-2026 Guillaume Kulakowski <guillaume@kulakowski.fr> 

3# 

4# For the full copyright and license information, please view the LICENSE 

5# file that was distributed with this source code. 

6# 

7"""SeedboxSync front cache module.""" 

8 

9from collections.abc import Callable 

10from typing import Any 

11from flask import request, session 

12from flask_caching import Cache 

13from flask_login import current_user 

14from seedboxsync.core import current_app 

15 

16# Global Flask-Caching instance 

17cache = Cache() 

18 

19 

20def make_user_cache_key() -> str: 

21 """ 

22 Generate a dynamic cache key based on the user's authentication state[cite: 1]. 

23 

24 Appends the authenticated user ID or an 'anonymous' flag to the request path 

25 to ensure cached responses are segregated between logged-in and anonymous sessions. 

26 

27 Returns: 

28 str: Generated cache key combining the request path and user status. 

29 """ 

30 if current_app.config["LOGIN_DISABLED"]: 

31 return f"{request.path}_login_disabled" 

32 

33 user_status = f"user_{current_user.id}" if current_user.is_authenticated else "anonymous" 

34 return f"{request.path}_{user_status}" 

35 

36 

37def cached(timeout: int = 300) -> Callable[..., Any]: 

38 """ 

39 Custom cached decorator enforcing user-aware cache keys. 

40 

41 Args: 

42 timeout (int): Cache expiration timeout in seconds. Defaults to 300. 

43 

44 Returns: 

45 Callable[..., Any]: Flask-Caching cached decorator configured with make_user_cache_key. 

46 """ 

47 return cache.cached(make_cache_key=make_user_cache_key, timeout=timeout, unless=lambda: bool(session.get("_flashes")))