Browse Source

Make FastAPI's root_path take precedence

pull/11160/head
Ricardo Madriz 1 year ago
parent
commit
390540eebd
  1. 18
      fastapi/applications.py
  2. 16
      tests/test_root_path_redirects.py

18
fastapi/applications.py

@ -1052,19 +1052,19 @@ class FastAPI(Starlette):
if self.root_path:
root_path = scope.get("root_path", "")
if root_path and self.root_path != root_path:
raise RuntimeError(
logger.warning(
f"The ASGI server is using a different root path than the one "
f"configured in FastAPI. The configured root path is: "
f"{self.root_path}, the ASGI server root path is: {root_path}. "
f"The former will be used."
)
else:
scope["root_path"] = self.root_path
path = scope.get("path")
if path and not path.startswith(self.root_path):
scope["path"] = self.root_path + path
raw_path: bytes | None = scope.get("raw_path")
if raw_path and not raw_path.startswith(self.root_path.encode()):
scope["raw_path"] = self.root_path.encode() + raw_path
scope["root_path"] = self.root_path
path = scope.get("path")
if path and not path.startswith(self.root_path):
scope["path"] = self.root_path + path
raw_path: bytes | None = scope.get("raw_path")
if raw_path and not raw_path.startswith(self.root_path.encode()):
scope["raw_path"] = self.root_path.encode() + raw_path
await super().__call__(scope, receive, send)
def add_api_route(

16
tests/test_root_path_redirects.py

@ -34,3 +34,19 @@ def test_redirects_with_root_path():
response = client.get("/hello", follow_redirects=False)
assert response.status_code == 307
assert response.headers["location"] == "http://testserver/api/hello/"
def test_invalid_combination_of_root_path():
app = FastAPI(root_path="/api")
router = APIRouter()
@router.get("/hello/")
def hello_page() -> str:
return "Hello, World!"
app.include_router(router)
client = TestClient(app, base_url="http://testserver", root_path="/notapi")
response = client.get("/hello", follow_redirects=False)
assert response.status_code == 307
assert response.headers["location"] == "http://testserver/api/hello/"

Loading…
Cancel
Save