Coverage for opt/mealie/lib/python3.12/site-packages/mealie/routes/_base/routers.py: 100%

27 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-11-25 15:32 +0000

1import contextlib 1a

2import json 1a

3from collections.abc import Callable 1a

4from enum import Enum 1a

5from json.decoder import JSONDecodeError 1a

6 

7from fastapi import APIRouter, Depends, Request, Response 1a

8from fastapi.routing import APIRoute 1a

9 

10from mealie.core.dependencies import get_admin_user, get_current_user 1a

11 

12 

13class AdminAPIRouter(APIRouter): 1a

14 """Router for functions to be protected behind admin authentication""" 

15 

16 def __init__(self, tags: list[str | Enum] | None = None, prefix: str = "", **kwargs): 1a

17 super().__init__(tags=tags, prefix=prefix, dependencies=[Depends(get_admin_user)], **kwargs) 1a

18 

19 

20class UserAPIRouter(APIRouter): 1a

21 """Router for functions to be protected behind user authentication""" 

22 

23 def __init__(self, tags: list[str | Enum] | None = None, prefix: str = "", **kwargs): 1a

24 super().__init__(tags=tags, prefix=prefix, dependencies=[Depends(get_current_user)], **kwargs) 1a

25 

26 

27class MealieCrudRoute(APIRoute): 1a

28 """Route class to include the last-modified header when returning a MealieModel, when available""" 

29 

30 def get_route_handler(self) -> Callable: 1a

31 original_route_handler = super().get_route_handler() 1a

32 

33 async def custom_route_handler(request: Request) -> Response: 1a

34 with contextlib.suppress(JSONDecodeError): 1kmbcdelfghij

35 response = await original_route_handler(request) 1kmbcdelfghij

36 response_body = json.loads(response.body) 1kbcdelfghij

37 if isinstance(response_body, dict): 1kbcdelfghij

38 if last_modified := response_body.get("updatedAt"): 1kbcdelfghij

39 response.headers["last-modified"] = last_modified 1bcdefghij

40 

41 # Force no-cache for all responses to prevent browser from caching API calls 

42 response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" 1bcdefghij

43 return response 1kbcdelfghij

44 

45 return custom_route_handler 1a