Skip to content

Commit

Permalink
Add a UUID convertor (#903)
Browse files Browse the repository at this point in the history
* Implement UUID path param converter

* Add the uuid convertor to the docs
  • Loading branch information
JayH5 committed Apr 21, 2020
1 parent 678f87d commit 9440fd7
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/routing.md
Expand Up @@ -43,6 +43,7 @@ You can use convertors to modify what is captured. Four convertors are available
* `str` returns a string, and is the default.
* `int` returns a Python integer.
* `float` returns a Python float.
* `uuid` return a Python `uuid.UUID` instance.
* `path` returns the rest of the path, including any additional `/` characers.

Convertors are used by prefixing them with a colon, like so:
Expand Down
12 changes: 12 additions & 0 deletions starlette/convertors.py
@@ -1,5 +1,6 @@
import math
import typing
import uuid


class Convertor:
Expand Down Expand Up @@ -61,9 +62,20 @@ def to_string(self, value: typing.Any) -> str:
return ("%0.20f" % value).rstrip("0").rstrip(".")


class UUIDConvertor(Convertor):
regex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"

def convert(self, value: str) -> typing.Any:
return uuid.UUID(value)

def to_string(self, value: typing.Any) -> str:
return str(value)


CONVERTOR_TYPES = {
"str": StringConvertor(),
"path": PathConvertor(),
"int": IntegerConvertor(),
"float": FloatConvertor(),
"uuid": UUIDConvertor(),
}
19 changes: 19 additions & 0 deletions tests/test_routing.py
@@ -1,3 +1,5 @@
import uuid

import pytest

from starlette.applications import Starlette
Expand Down Expand Up @@ -75,6 +77,12 @@ def path_convertor(request):
return JSONResponse({"path": path})


@app.route("/uuid/{param:uuid}", name="uuid-convertor")
def uuid_converter(request):
uuid_param = request.path_params["param"]
return JSONResponse({"uuid": str(uuid_param)})


@app.websocket_route("/ws")
async def websocket_endpoint(session):
await session.accept()
Expand Down Expand Up @@ -152,6 +160,17 @@ def test_route_converters():
app.url_path_for("path-convertor", param="some/example") == "/path/some/example"
)

# Test UUID conversion
response = client.get("/uuid/ec38df32-ceda-4cfa-9b4a-1aeb94ad551a")
assert response.status_code == 200
assert response.json() == {"uuid": "ec38df32-ceda-4cfa-9b4a-1aeb94ad551a"}
assert (
app.url_path_for(
"uuid-convertor", param=uuid.UUID("ec38df32-ceda-4cfa-9b4a-1aeb94ad551a")
)
== "/uuid/ec38df32-ceda-4cfa-9b4a-1aeb94ad551a"
)


def test_url_path_for():
assert app.url_path_for("homepage") == "/"
Expand Down

0 comments on commit 9440fd7

Please sign in to comment.