Coverage for mcpgateway / middleware / request_context.py: 100%

7 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-02-11 07:10 +0000

1# -*- coding: utf-8 -*- 

2"""Small helpers for per-request caching. 

3 

4Copyright 2025 

5SPDX-License-Identifier: Apache-2.0 

6 

7This module provides optional helpers for caching request metadata on 

8request.state to avoid repeated property access in hot paths. 

9 

10Note: This is an optional optimization. Use only if profiling shows 

11repeated request.url.path access as a hotspot. 

12""" 

13 

14# Third-Party 

15from starlette.requests import Request 

16 

17 

18def get_request_path(request: Request) -> str: 

19 """Return cached request path (stores once in request.state). 

20 

21 Caches the path on first access to avoid repeated URL parsing 

22 in middleware that check paths multiple times. 

23 

24 IMPORTANT: Uses request.url.path (not request.scope["path"]) to preserve 

25 behavior with root_path/mounts when deployed behind proxies. 

26 

27 Note: Uses _cached_path as a namespaced internal attribute on request.state 

28 to avoid conflicts with user-defined attributes. 

29 

30 Args: 

31 request: The Starlette/FastAPI request object 

32 

33 Returns: 

34 The request URL path string 

35 

36 Examples: 

37 >>> from unittest.mock import MagicMock 

38 >>> request = MagicMock() 

39 >>> request.state = MagicMock() 

40 >>> request.state._cached_path = None 

41 >>> request.url.path = "/api/tools" 

42 >>> # First call stores in cache 

43 >>> get_request_path(request) # doctest: +SKIP 

44 '/api/tools' 

45 """ 

46 cached = getattr(request.state, "_cached_path", None) 

47 if cached is None: 

48 cached = request.url.path 

49 setattr(request.state, "_cached_path", cached) 

50 return cached