Skip to content

Commit

Permalink
fix pydantic return type serializer to support lists (#17)
Browse files Browse the repository at this point in the history
  • Loading branch information
thrau authored Jul 20, 2024
1 parent 8603832 commit b51ca31
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ name = "rolo"
authors = [
{ name = "LocalStack Contributors", email = "[email protected]" }
]
version = "0.6.0"
version = "0.6.1"
description = "A Python framework for building HTTP-based server applications"
dependencies = [
"requests>=2.20",
Expand Down
8 changes: 8 additions & 0 deletions rolo/dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,14 @@ def _dispatch(request: Request, endpoint: Handler, args: RequestArguments) -> Re

if isinstance(result, pydantic.BaseModel):
result = result.model_dump()
if isinstance(result, (list, tuple)):
converted = []
for element in result:
if isinstance(element, pydantic.BaseModel):
converted.append(element.model_dump())
else:
converted.append(element)
result = converted

else:
result = endpoint(request, **args)
Expand Down
25 changes: 25 additions & 0 deletions tests/test_pydantic.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,31 @@ def handler(_request: Request, item_id: int) -> MyItem:
"is_offer": None,
}

def test_response_list(self):
router = Router(dispatcher=handler_dispatcher())

def handler(_request: Request) -> list[MyItem]:
return [
MyItem(name="rolo", price=420.69),
MyItem(name="twiks", price=1.23, is_offer=True),
]

router.add("/items", handler)

request = Request("GET", "/items")
assert router.dispatch(request).get_json() == [
{
"name": "rolo",
"price": 420.69,
"is_offer": None,
},
{
"name": "twiks",
"price": 1.23,
"is_offer": True,
},
]

def test_request_arg_validation_error(self):
router = Router(dispatcher=handler_dispatcher())

Expand Down

0 comments on commit b51ca31

Please sign in to comment.