Skip to content

Commit ad56ab1

Browse files
committed
fix: improve UploadFile Pydantic schema compatibility
- Fixed Pydantic core schema generation for UploadFile class - Updated JSON schema method for better OpenAPI compatibility - Added proper type annotations for mypy compliance - Maintains all existing functionality while fixing schema generation issues Addresses reviewer feedback on code quality and type safety.
1 parent 8d48eba commit ad56ab1

File tree

1 file changed

+19
-16
lines changed
  • aws_lambda_powertools/event_handler/openapi

1 file changed

+19
-16
lines changed

aws_lambda_powertools/event_handler/openapi/params.py

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -114,14 +114,23 @@ def __get_pydantic_core_schema__(
114114
"""Return Pydantic core schema for UploadFile."""
115115
from pydantic_core import core_schema
116116

117-
# Define the schema for UploadFile validation
118-
schema = core_schema.no_info_plain_validator_function(
119-
cls._validate,
117+
# Use a string schema with custom JSON schema for OpenAPI
118+
return core_schema.with_info_plain_validator_function(
119+
cls._validate_with_info,
120120
serialization=core_schema.to_string_ser_schema(),
121121
)
122122

123-
# For OpenAPI schema info, we'll use __modify_schema__ method instead
124-
return schema
123+
@classmethod
124+
def _validate_with_info(cls, value: Any, info) -> UploadFile:
125+
"""Validate and convert value to UploadFile with validation info."""
126+
if isinstance(value, cls):
127+
return value
128+
if isinstance(value, bytes):
129+
return cls(file=value)
130+
# For OpenAPI schema generation, return a placeholder
131+
if info and getattr(info, "context", {}).get("openapi_generation", False):
132+
return cls(file=b"", filename="placeholder.txt")
133+
raise ValueError(f"Expected UploadFile or bytes, got {type(value)}")
125134

126135
@classmethod
127136
def __modify_schema__(cls, field_schema: dict[str, Any]) -> None:
@@ -151,17 +160,11 @@ def __get_validators__(cls):
151160
@classmethod
152161
def __get_pydantic_json_schema__(cls, _core_schema: Any, field_schema: Any) -> dict[str, Any]:
153162
"""Modify the JSON schema for OpenAPI compatibility."""
154-
# Handle both Pydantic v1 and v2 schemas
155-
json_schema = field_schema(_core_schema) if callable(field_schema) else {}
156-
157-
# Add binary file format for OpenAPI
158-
json_schema.update(
159-
type="string",
160-
format="binary",
161-
description="A file uploaded as part of a multipart/form-data request",
162-
)
163-
164-
return json_schema
163+
return {
164+
"type": "string",
165+
"format": "binary",
166+
"description": "A file uploaded as part of a multipart/form-data request",
167+
}
165168

166169

167170
class ParamTypes(Enum):

0 commit comments

Comments
 (0)