Browse Source

Merge 6240dc105a into eb75fd078e

pull/14928/merge
Charis Nikolaidis 4 days ago
committed by GitHub
parent
commit
4697eefddb
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 18
      fastapi/routing.py

18
fastapi/routing.py

@ -8,6 +8,7 @@ import json
import os
import stat
import types
import weakref
from collections.abc import (
AsyncIterator,
Awaitable,
@ -263,16 +264,19 @@ class _DefaultLifespan:
return self
# Cache for endpoint context to avoid re-extracting on every request
_endpoint_context_cache: dict[int, EndpointContext] = {}
# Cache for endpoint context to avoid re-extracting on every request.
# Uses WeakKeyDictionary so entries are automatically evicted when the endpoint
# function is garbage collected (e.g., when a dynamically created FastAPI app is
# destroyed), preventing both memory leaks and stale-ID lookups.
_endpoint_context_cache: weakref.WeakKeyDictionary[
Callable[..., Any], EndpointContext
] = weakref.WeakKeyDictionary()
def _extract_endpoint_context(func: Any) -> EndpointContext:
"""Extract endpoint context with caching to avoid repeated file I/O."""
func_id = id(func)
if func_id in _endpoint_context_cache:
return _endpoint_context_cache[func_id]
if func in _endpoint_context_cache:
return _endpoint_context_cache[func]
try:
ctx: EndpointContext = {}
@ -286,7 +290,7 @@ def _extract_endpoint_context(func: Any) -> EndpointContext:
except Exception:
ctx = EndpointContext()
_endpoint_context_cache[func_id] = ctx
_endpoint_context_cache[func] = ctx
return ctx

Loading…
Cancel
Save