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

Allow path to contain regex meta characters #932

Merged
merged 4 commits into from
May 11, 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions starlette/routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ def compile_path(
), f"Unknown path convertor '{convertor_type}'"
convertor = CONVERTOR_TYPES[convertor_type]

path_regex += path[idx : match.start()]
path_regex += re.escape(path[idx : match.start()])
path_regex += f"(?P<{param_name}>{convertor.regex})"

path_format += path[idx : match.start()]
Expand All @@ -117,7 +117,7 @@ def compile_path(

idx = match.end()

path_regex += path[idx:] + "$"
path_regex += re.escape(path[idx:]) + "$"
path_format += path[idx:]

return re.compile(path_regex), path_format, param_convertors
Expand Down
16 changes: 16 additions & 0 deletions tests/test_routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,13 @@ def uuid_converter(request):
return JSONResponse({"uuid": str(uuid_param)})


# Route with chars that conflict with regex meta chars
@app.route("/path-with-parentheses({param:int})", name="path-with-parentheses")
def path_with_parentheses(request):
number = request.path_params["param"]
return JSONResponse({"int": number})
peso marked this conversation as resolved.
Show resolved Hide resolved


@app.websocket_route("/ws")
async def websocket_endpoint(session):
await session.accept()
Expand Down Expand Up @@ -146,6 +153,15 @@ def test_route_converters():
assert response.json() == {"int": 5}
assert app.url_path_for("int-convertor", param=5) == "/int/5"

# Test path with parentheses
response = client.get("/path-with-parentheses(7)")
assert response.status_code == 200
assert response.json() == {"int": 7}
assert (
app.url_path_for("path-with-parentheses", param=7)
== "/path-with-parentheses(7)"
)

# Test float conversion
response = client.get("/float/25.5")
assert response.status_code == 200
Expand Down