Skip to content

Commit

Permalink
chore: Allow pydantic.BaseModel as API handler return schema (#1987)
Browse files Browse the repository at this point in the history
  • Loading branch information
fregataa committed Apr 4, 2024
1 parent e15b21e commit 652c1aa
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 3 deletions.
1 change: 1 addition & 0 deletions changes/1987.misc.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Allow `pydantic.BaseModel` as the API handler return schema.
8 changes: 5 additions & 3 deletions src/ai/backend/manager/api/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,12 +214,12 @@ async def wrapped(request: web.Request, *args: P.args, **kwargs: P.kwargs) -> TA


class BaseResponseModel(BaseModel):
status: Annotated[int, Field(strict=True, ge=100, lt=600)] = 200
status: Annotated[int, Field(strict=True, exclude=True, ge=100, lt=600)] = 200


TParamModel = TypeVar("TParamModel", bound=BaseModel)
TQueryModel = TypeVar("TQueryModel", bound=BaseModel)
TResponseModel = TypeVar("TResponseModel", bound=BaseResponseModel)
TResponseModel = TypeVar("TResponseModel", bound=BaseModel)

TPydanticResponse: TypeAlias = TResponseModel | list
THandlerFuncWithoutParam: TypeAlias = Callable[
Expand All @@ -231,11 +231,13 @@ class BaseResponseModel(BaseModel):


def ensure_stream_response_type(
response: BaseResponseModel | list[TResponseModel] | web.StreamResponse,
response: BaseResponseModel | BaseModel | list[TResponseModel] | web.StreamResponse,
) -> web.StreamResponse:
match response:
case BaseResponseModel(status=status):
return web.json_response(response.model_dump(mode="json"), status=status)
case BaseModel():
return web.json_response(response.model_dump(mode="json"))
case list():
return web.json_response(TypeAdapter(type(response)).dump_python(response, mode="json"))
case web.StreamResponse():
Expand Down

0 comments on commit 652c1aa

Please sign in to comment.