diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index b73473484..dc6eab8b2 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -542,7 +542,8 @@ async def solve_dependencies( response = Response() del response.headers["content-length"] response.status_code = None # type: ignore - dependency_cache = dependency_cache or {} + if dependency_cache is None: + dependency_cache = {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) @@ -566,6 +567,13 @@ async def solve_dependencies( name=sub_dependant.name, security_scopes=sub_dependant.security_scopes, ) + if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache: + solved = dependency_cache[sub_dependant.cache_key] + + if sub_dependant.name is not None: + values[sub_dependant.name] = solved + + continue solved_result = await solve_dependencies( request=request, @@ -588,8 +596,6 @@ async def solve_dependencies( if sub_errors: errors.extend(sub_errors) continue - if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache: - solved = dependency_cache[sub_dependant.cache_key] elif is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=sub_values diff --git a/tests/test_dependency_cache.py b/tests/test_dependency_cache.py index 691a62b45..a1719d808 100644 --- a/tests/test_dependency_cache.py +++ b/tests/test_dependency_cache.py @@ -1,14 +1,24 @@ from fastapi import Depends, FastAPI, Security +from fastapi._compat import PYDANTIC_V2 from fastapi.testclient import TestClient -from pydantic import BaseModel, root_validator +from pydantic import BaseModel app = FastAPI() counter_holder = {"counter": 0, "parsing_counter": 0} +if PYDANTIC_V2: + from pydantic import model_validator + + decorator = model_validator(mode="before") +else: + from pydantic import root_validator + + decorator = root_validator + class Model(BaseModel): - @root_validator + @decorator def __validate__(cls, _): counter_holder["parsing_counter"] += 1 return {}