Fix slash redirects (#812)

* Fix for slash redirects

* Drop extranous 'type: ignore'

* Drop print() statement

* Add type: ignore on optional imports
This commit is contained in:
Tom Christie 2020-01-29 09:48:35 +00:00 committed by GitHub
parent 6a65461c6e
commit 508ab752b4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 21 additions and 14 deletions

View File

@ -15,9 +15,9 @@ try:
from graphql.error import GraphQLError
except ImportError: # pragma: nocover
graphene = None
AsyncioExecutor = None
format_graphql_error = None
GraphQLError = None
AsyncioExecutor = None # type: ignore
format_graphql_error = None # type: ignore
GraphQLError = None # type: ignore
class GraphQLApp:

View File

@ -561,18 +561,20 @@ class Router:
await partial.handle(scope, receive, send)
return
if scope["type"] == "http" and self.redirect_slashes:
if not scope["path"].endswith("/"):
redirect_scope = dict(scope)
redirect_scope["path"] += "/"
if scope["type"] == "http" and self.redirect_slashes and scope["path"] != "/":
redirect_scope = dict(scope)
if scope["path"].endswith("/"):
redirect_scope["path"] = redirect_scope["path"].rstrip("/")
else:
redirect_scope["path"] = redirect_scope["path"] + "/"
for route in self.routes:
match, child_scope = route.matches(redirect_scope)
if match != Match.NONE:
redirect_url = URL(scope=redirect_scope)
response = RedirectResponse(url=str(redirect_url))
await response(scope, receive, send)
return
for route in self.routes:
match, child_scope = route.matches(redirect_scope)
if match != Match.NONE:
redirect_url = URL(scope=redirect_scope)
response = RedirectResponse(url=str(redirect_url))
await response(scope, receive, send)
return
await self.default(scope, receive, send)

View File

@ -117,6 +117,11 @@ def test_router():
assert response.status_code == 200
assert response.text == "User fixed me"
response = client.get("/users/tomchristie/")
assert response.status_code == 200
assert response.url == "http://testserver/users/tomchristie"
assert response.text == "User tomchristie"
response = client.get("/users/nomatch")
assert response.status_code == 200
assert response.text == "User nomatch"