Starlette: Strip trailing slash ( / ) from URL route strings.

Created on 4 Sep 2019  路  6Comments  路  Source: encode/starlette

Hey all, an optional trailing slash seems to be pretty standard on most websites, but in Starlette, you must add separate routes to handle them. Example:

routes = [
    Route('/', PlainTextResponse("home")),
    Route('/test', PlainTextResponse("test")),
    Route('/test/', PlainTextResponse("I need to be added separately?!"))
]

app = Starlette(routes=routes)

Could a route = route.rstrip("/") please be added to https://github.com/encode/starlette/blob/master/starlette/routing.py in class Router before running the match so these routes don't have to be manually added? Thanks!

Most helpful comment

I am seeing this issue again. From the history of routing.py it looks like #707 might have been reverted by #704?

All 6 comments

Not sure about this myself - seems like a bit too much magic to have by default.

But you might want to create a PR with your suggested patch already, so this can be discussed at the code level.

btw: you can use "/path/?" to match an optional slash..

Absolutely, yup.

We already handle the converse case, but for some reason I've only got the behavior in one way right now.

python routes = [ Route('/', PlainTextResponse("home")), Route('/test/', PlainTextResponse("test")), # Route('/test', PlainTextResponse("I do not need to be added separately")) ]

I am seeing this issue again. From the history of routing.py it looks like #707 might have been reverted by #704?

Yeah, too bad https://github.com/encode/starlette/pull/707 did not have a test.
@tomchristie please re-open / fix it.
@achien might be helpful to know which commit from #704 it was - have not checked it myself, but there are several.

@blueyed it looks like the merge commit caused the regression https://github.com/encode/starlette/pull/704/files#diff-34fba745b50527bfb4245d02afd59246, specifically around line 617 of the old version and 564 of the new version.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dgrahn picture dgrahn  路  4Comments

rugleb picture rugleb  路  4Comments

rlewkowicz picture rlewkowicz  路  3Comments

koddr picture koddr  路  6Comments

PeriGK picture PeriGK  路  5Comments