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

Fix optional route bug #1010

Closed
wants to merge 1 commit into from
Closed
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
7 changes: 6 additions & 1 deletion starlette/routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,12 @@ def compile_path(

idx = match.end()

path_regex += re.escape(path[idx:]) + "$"
# Prevent the escape of ? for route ending with ?
if path[-1] == "?":
path_regex += re.escape(path[idx:-1]) + "?$"
else:
path_regex += re.escape(path[idx:]) + "$"

path_format += path[idx:]

return re.compile(path_regex), path_format, param_convertors
Expand Down
15 changes: 15 additions & 0 deletions tests/test_routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,12 @@ def path_with_parentheses(request):
return JSONResponse({"int": number})


# Route with chars that conflict with regex meta chars
@app.route("/optional-path/?", name="optional-path")
def optional_path(request):
return Response("Optional path reached.", media_type="text/plain")


@app.websocket_route("/ws")
async def websocket_endpoint(session):
await session.accept()
Expand Down Expand Up @@ -162,6 +168,15 @@ def test_route_converters():
== "/path-with-parentheses(7)"
)

# Test optional path
response = client.get("/optional-path")
assert response.status_code == 200
assert response.text == "Optional path reached."

response = client.get("/optional-path/")
assert response.status_code == 200
assert response.text == "Optional path reached."

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