Browse Source

perf: optimize OpenAPI response class status code detection

Add caching mechanism for default_status_code attribute to avoid
repeated signature inspection, improving schema generation performance.
pull/13874/head
kim 2 weeks ago
parent
commit
0b567f86b2
  1. 10
      fastapi/openapi/utils.py

10
fastapi/openapi/utils.py

@ -338,11 +338,11 @@ def get_openapi_path(
if route.status_code is not None: if route.status_code is not None:
status_code = str(route.status_code) status_code = str(route.status_code)
else: else:
# It would probably make more sense for all response classes to have an # Use cached attribute if available, otherwise fall back to inspection
# explicit default status_code, and to extract it from them, instead of # This improves performance by avoiding repeated signature inspection
# doing this inspection tricks, that would probably be in the future if hasattr(current_response_class, "default_status_code"):
# TODO: probably make status_code a default class attribute for all status_code = str(current_response_class.default_status_code)
# responses in Starlette else:
response_signature = inspect.signature(current_response_class.__init__) response_signature = inspect.signature(current_response_class.__init__)
status_code_param = response_signature.parameters.get("status_code") status_code_param = response_signature.parameters.get("status_code")
if status_code_param is not None: if status_code_param is not None:

Loading…
Cancel
Save