Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a UUID convertor #903

Merged
merged 2 commits into from Apr 21, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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