Skip to content

Commit

Permalink
Make UUID path parameter conversion more flexible (#2806)
Browse files Browse the repository at this point in the history
  • Loading branch information
edthrn authored Dec 25, 2024
1 parent c82acf3 commit cba90a7
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
2 changes: 1 addition & 1 deletion starlette/convertors.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def to_string(self, value: float) -> str:


class UUIDConvertor(Convertor[uuid.UUID]):
regex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
regex = "[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12}"

def convert(self, value: str) -> uuid.UUID:
return uuid.UUID(value)
Expand Down
24 changes: 24 additions & 0 deletions tests/test_convertors.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from datetime import datetime
from typing import Iterator
from uuid import UUID

import pytest

Expand Down Expand Up @@ -70,3 +71,26 @@ def float_convertor(request: Request) -> JSONResponse:
client = test_client_factory(app)
response = client.get(f"/{param}")
assert response.status_code == status_code


@pytest.mark.parametrize(
"param, status_code",
[
("00000000-aaaa-ffff-9999-000000000000", 200),
("00000000aaaaffff9999000000000000", 200),
("00000000-AAAA-FFFF-9999-000000000000", 200),
("00000000AAAAFFFF9999000000000000", 200),
("not-a-uuid", 404),
],
)
def test_default_uuid_convertor(test_client_factory: TestClientFactory, param: str, status_code: int) -> None:
def uuid_convertor(request: Request) -> JSONResponse:
param = request.path_params["param"]
assert isinstance(param, UUID)
return JSONResponse("ok")

app = Router(routes=[Route("/{param:uuid}", endpoint=uuid_convertor)])

client = test_client_factory(app)
response = client.get(f"/{param}")
assert response.status_code == status_code

0 comments on commit cba90a7

Please sign in to comment.