Skip to content

Commit 5b31cc0

Browse files
committed
making {uuid:var} backward compatible
1 parent ffe68f4 commit 5b31cc0

File tree

3 files changed

+24
-4
lines changed

3 files changed

+24
-4
lines changed

ninja/router.py

+8
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,14 @@ def add_api_operation(
320320
include_in_schema: bool = True,
321321
openapi_extra: Optional[Dict[str, Any]] = None,
322322
) -> None:
323+
324+
if "{uuid:" in path:
325+
# django by default convert strings to UUIDs
326+
# but we want to keep them as strings to let pydantic handle conversion/validation
327+
# if user whants UUID object
328+
# uuidstr is custom registered converter
329+
path = path.replace("{uuid:", "{uuidstr:")
330+
323331
if path not in self.path_operations:
324332
path_view = PathView()
325333
self.path_operations[path] = path_view

tests/main.py

+9-2
Original file line numberDiff line numberDiff line change
@@ -174,8 +174,15 @@ def get_path_param_django_uuid(request, item_id: UUID):
174174
return item_id
175175

176176

177-
@router.get("/path/param-django-uuid-str/{uuidstr:item_id}")
178-
def get_path_param_django_uuid_str(request, item_id):
177+
@router.get("/path/param-django-uuid-notype/{uuid:item_id}")
178+
def get_path_param_django_uuid_notype(request, item_id):
179+
# no type annotation defaults to str..............^
180+
assert isinstance(item_id, str)
181+
return item_id
182+
183+
184+
@router.get("/path/param-django-uuid-typestr/{uuid:item_id}")
185+
def get_path_param_django_uuid_typestr(request, item_id: str):
179186
assert isinstance(item_id, str)
180187
return item_id
181188

tests/test_path.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -301,12 +301,17 @@ def test_get_path(path, expected_status, expected_response):
301301
"31ea378c-c052-4b4c-bf0b-679ce5cfcc2a",
302302
),
303303
(
304-
"/path/param-django-uuid/31ea378c-c052-4b4c-bf0b-679ce5cfcc2",
304+
"/path/param-django-uuid/31ea378c-c052-4b4c-bf0b-679ce5cfcc2", # invalid UUID (missing last digit)
305305
"Cannot resolve",
306306
Exception,
307307
),
308308
(
309-
"/path/param-django-uuid-str/31ea378c-c052-4b4c-bf0b-679ce5cfcc2a",
309+
"/path/param-django-uuid-notype/31ea378c-c052-4b4c-bf0b-679ce5cfcc2a",
310+
200,
311+
"31ea378c-c052-4b4c-bf0b-679ce5cfcc2a",
312+
),
313+
(
314+
"/path/param-django-uuid-typestr/31ea378c-c052-4b4c-bf0b-679ce5cfcc2a",
310315
200,
311316
"31ea378c-c052-4b4c-bf0b-679ce5cfcc2a",
312317
),

0 commit comments

Comments
 (0)