diff --git a/docs/de/docs/how-to/custom-docs-ui-assets.md b/docs/de/docs/how-to/custom-docs-ui-assets.md index f68902b99..cd2287a31 100644 --- a/docs/de/docs/how-to/custom-docs-ui-assets.md +++ b/docs/de/docs/how-to/custom-docs-ui-assets.md @@ -18,7 +18,7 @@ Der erste Schritt besteht darin, die automatischen Dokumentationen zu deaktivier Um diese zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`: -{* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *} +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[12] *} ### Die benutzerdefinierten Dokumentationen hinzufügen @@ -34,7 +34,7 @@ Sie können die internen Funktionen von FastAPI wiederverwenden, um die HTML-Sei Und genau so für ReDoc ... -{* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:19,22:24,27:33] *} +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[4:8,15:24,27:29,32:39] *} /// tip | Tipp @@ -50,7 +50,7 @@ Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „U Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*: -{* ../../docs_src/custom_docs_ui/tutorial001.py hl[36:38] *} +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[42:44] *} ### Es ausprobieren @@ -118,7 +118,7 @@ Danach könnte Ihre Dateistruktur wie folgt aussehen: * Importieren Sie `StaticFiles`. * „Mounten“ Sie eine `StaticFiles()`-Instanz in einem bestimmten Pfad. -{* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *} +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9,15] *} ### Die statischen Dateien testen @@ -144,7 +144,7 @@ Wie bei der Verwendung eines benutzerdefinierten CDN besteht der erste Schritt d Um diese zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`: -{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *} +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[13] *} ### Die benutzerdefinierten Dokumentationen, mit statischen Dateien, hinzufügen @@ -160,7 +160,7 @@ Auch hier können Sie die internen Funktionen von FastAPI wiederverwenden, um di Und genau so für ReDoc ... -{* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:22,25:27,30:36] *} +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[4:8,18:27,30:32,35:42] *} /// tip | Tipp @@ -176,7 +176,7 @@ Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „U Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*: -{* ../../docs_src/custom_docs_ui/tutorial002.py hl[39:41] *} +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[45:47] *} ### Benutzeroberfläche, mit statischen Dateien, testen diff --git a/docs/en/docs/how-to/custom-docs-ui-assets.md b/docs/en/docs/how-to/custom-docs-ui-assets.md index 9d2238e4f..611cfca1e 100644 --- a/docs/en/docs/how-to/custom-docs-ui-assets.md +++ b/docs/en/docs/how-to/custom-docs-ui-assets.md @@ -18,7 +18,7 @@ The first step is to disable the automatic docs, as by default, those use the de To disable them, set their URLs to `None` when creating your `FastAPI` app: -{* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *} +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[12] *} ### Include the custom docs @@ -34,7 +34,7 @@ You can reuse FastAPI's internal functions to create the HTML pages for the docs And similarly for ReDoc... -{* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:19,22:24,27:33] *} +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[4:8,15:24,27:29,32:39] *} /// tip @@ -50,7 +50,7 @@ Swagger UI will handle it behind the scenes for you, but it needs this "redirect Now, to be able to test that everything works, create a *path operation*: -{* ../../docs_src/custom_docs_ui/tutorial001.py hl[36:38] *} +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[42:44] *} ### Test it @@ -118,7 +118,7 @@ After that, your file structure could look like: * Import `StaticFiles`. * "Mount" a `StaticFiles()` instance in a specific path. -{* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *} +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9,15] *} ### Test the static files @@ -144,7 +144,7 @@ The same as when using a custom CDN, the first step is to disable the automatic To disable them, set their URLs to `None` when creating your `FastAPI` app: -{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *} +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[13] *} ### Include the custom docs for static files @@ -160,7 +160,7 @@ Again, you can reuse FastAPI's internal functions to create the HTML pages for t And similarly for ReDoc... -{* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:22,25:27,30:36] *} +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[4:8,18:27,30:32,35:42] *} /// tip @@ -176,7 +176,7 @@ Swagger UI will handle it behind the scenes for you, but it needs this "redirect Now, to be able to test that everything works, create a *path operation*: -{* ../../docs_src/custom_docs_ui/tutorial002.py hl[39:41] *} +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[45:47] *} ### Test Static Files UI diff --git a/docs/es/docs/how-to/custom-docs-ui-assets.md b/docs/es/docs/how-to/custom-docs-ui-assets.md index 0a03ff330..ae65ce2b3 100644 --- a/docs/es/docs/how-to/custom-docs-ui-assets.md +++ b/docs/es/docs/how-to/custom-docs-ui-assets.md @@ -18,7 +18,7 @@ El primer paso es desactivar la documentación automática, ya que por defecto, Para desactivarlos, establece sus URLs en `None` cuando crees tu aplicación de `FastAPI`: -{* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *} +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[12] *} ### Incluye la documentación personalizada @@ -34,7 +34,7 @@ Puedes reutilizar las funciones internas de FastAPI para crear las páginas HTML Y de manera similar para ReDoc... -{* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:19,22:24,27:33] *} +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[4:8,15:24,27:29,32:39] *} /// tip | Consejo @@ -50,7 +50,7 @@ Swagger UI lo manejará detrás de escena para ti, pero necesita este auxiliar d Ahora, para poder probar que todo funciona, crea una *path operation*: -{* ../../docs_src/custom_docs_ui/tutorial001.py hl[36:38] *} +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[42:44] *} ### Pruébalo @@ -118,7 +118,7 @@ Después de eso, tu estructura de archivos podría verse así: * Importa `StaticFiles`. * "Monta" una instance de `StaticFiles()` en un path específico. -{* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *} +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9,15] *} ### Prueba los archivos estáticos @@ -144,7 +144,7 @@ Igual que cuando usas un CDN personalizado, el primer paso es desactivar la docu Para desactivarlos, establece sus URLs en `None` cuando crees tu aplicación de `FastAPI`: -{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *} +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[13] *} ### Incluye la documentación personalizada para archivos estáticos @@ -160,7 +160,7 @@ Nuevamente, puedes reutilizar las funciones internas de FastAPI para crear las p Y de manera similar para ReDoc... -{* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:22,25:27,30:36] *} +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[4:8,18:27,30:32,35:42] *} /// tip | Consejo @@ -176,7 +176,7 @@ Swagger UI lo manejará detrás de escena para ti, pero necesita este auxiliar d Ahora, para poder probar que todo funciona, crea una *path operation*: -{* ../../docs_src/custom_docs_ui/tutorial002.py hl[39:41] *} +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[45:47] *} ### Prueba la UI de Archivos Estáticos diff --git a/docs/pt/docs/how-to/custom-docs-ui-assets.md b/docs/pt/docs/how-to/custom-docs-ui-assets.md index b7de6c8bd..b9d619cd6 100644 --- a/docs/pt/docs/how-to/custom-docs-ui-assets.md +++ b/docs/pt/docs/how-to/custom-docs-ui-assets.md @@ -18,7 +18,7 @@ O primeiro passo é desativar a documentação automática, pois por padrão, el Para desativá-los, defina suas URLs como `None` ao criar seu aplicativo `FastAPI`: -{* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *} +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[12] *} ### Incluir a documentação personalizada @@ -34,7 +34,7 @@ Você pode reutilizar as funções internas do FastAPI para criar as páginas HT E de forma semelhante para o ReDoc... -{* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:19,22:24,27:33] *} +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[4:8,15:24,27:29,32:39] *} /// tip | Dica @@ -50,7 +50,7 @@ Swagger UI lidará com isso nos bastidores para você, mas ele precisa desse aux Agora, para poder testar se tudo funciona, crie uma *operação de rota*: -{* ../../docs_src/custom_docs_ui/tutorial001.py hl[36:38] *} +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[42:44] *} ### Teste @@ -118,7 +118,7 @@ Depois disso, sua estrutura de arquivos deve se parecer com: * Importe `StaticFiles`. * "Monte" a instância `StaticFiles()` em um caminho específico. -{* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *} +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9,15] *} ### Teste os arquivos estáticos @@ -144,7 +144,7 @@ Da mesma forma que ao usar um CDN personalizado, o primeiro passo é desativar a Para desativá-los, defina suas URLs como `None` ao criar seu aplicativo `FastAPI`: -{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *} +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[13] *} ### Incluir a documentação personalizada para arquivos estáticos @@ -160,7 +160,7 @@ Novamente, você pode reutilizar as funções internas do FastAPI para criar as E de forma semelhante para o ReDoc... -{* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:22,25:27,30:36] *} +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[4:8,18:27,30:32,35:42] *} /// tip | Dica @@ -176,7 +176,7 @@ Swagger UI lidará com isso nos bastidores para você, mas ele precisa desse aux Agora, para poder testar se tudo funciona, crie uma *operação de rota*: -{* ../../docs_src/custom_docs_ui/tutorial002.py hl[39:41] *} +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[45:47] *} ### Teste a UI de Arquivos Estáticos diff --git a/docs_src/custom_docs_ui/tutorial001.py b/docs_src/custom_docs_ui/tutorial001.py index 1cfcce19a..fef8affe1 100644 --- a/docs_src/custom_docs_ui/tutorial001.py +++ b/docs_src/custom_docs_ui/tutorial001.py @@ -1,19 +1,24 @@ -from fastapi import FastAPI +import os + +from fastapi import FastAPI, Request from fastapi.openapi.docs import ( get_redoc_html, get_swagger_ui_html, get_swagger_ui_oauth2_redirect_html, ) -app = FastAPI(docs_url=None, redoc_url=None) +root_path = os.getenv("ROOT_PATH", "") + +app = FastAPI(docs_url=None, redoc_url=None, root_path=root_path) @app.get("/docs", include_in_schema=False) -async def custom_swagger_ui_html(): +async def custom_swagger_ui_html(req: Request): + root_path = req.scope.get("root_path", "").rstrip("/") return get_swagger_ui_html( - openapi_url=app.openapi_url, + openapi_url=f"{root_path}{app.openapi_url}", title=app.title + " - Swagger UI", - oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url, + oauth2_redirect_url=f"{root_path}{app.swagger_ui_oauth2_redirect_url}", swagger_js_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js", swagger_css_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css", ) @@ -25,9 +30,10 @@ async def swagger_ui_redirect(): @app.get("/redoc", include_in_schema=False) -async def redoc_html(): +async def redoc_html(req: Request): + root_path = req.scope.get("root_path", "").rstrip("/") return get_redoc_html( - openapi_url=app.openapi_url, + openapi_url=f"{root_path}{app.openapi_url}", title=app.title + " - ReDoc", redoc_js_url="https://unpkg.com/redoc@2/bundles/redoc.standalone.js", ) diff --git a/docs_src/custom_docs_ui/tutorial002.py b/docs_src/custom_docs_ui/tutorial002.py index 23ea368f8..91df12710 100644 --- a/docs_src/custom_docs_ui/tutorial002.py +++ b/docs_src/custom_docs_ui/tutorial002.py @@ -1,4 +1,6 @@ -from fastapi import FastAPI +import os + +from fastapi import FastAPI, Request from fastapi.openapi.docs import ( get_redoc_html, get_swagger_ui_html, @@ -6,19 +8,22 @@ from fastapi.openapi.docs import ( ) from fastapi.staticfiles import StaticFiles -app = FastAPI(docs_url=None, redoc_url=None) +root_path = os.getenv("ROOT_PATH", "") + +app = FastAPI(docs_url=None, redoc_url=None, root_path=root_path) app.mount("/static", StaticFiles(directory="static"), name="static") @app.get("/docs", include_in_schema=False) -async def custom_swagger_ui_html(): +async def custom_swagger_ui_html(req: Request): + root_path = req.scope.get("root_path", "").rstrip("/") return get_swagger_ui_html( - openapi_url=app.openapi_url, + openapi_url=f"{root_path}{app.openapi_url}", title=app.title + " - Swagger UI", - oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url, - swagger_js_url="/static/swagger-ui-bundle.js", - swagger_css_url="/static/swagger-ui.css", + oauth2_redirect_url=f"{root_path}{app.swagger_ui_oauth2_redirect_url}", + swagger_js_url=f"{root_path}/static/swagger-ui-bundle.js", + swagger_css_url=f"{root_path}/static/swagger-ui.css", ) @@ -28,11 +33,12 @@ async def swagger_ui_redirect(): @app.get("/redoc", include_in_schema=False) -async def redoc_html(): +async def redoc_html(req: Request): + root_path = req.scope.get("root_path", "").rstrip("/") return get_redoc_html( - openapi_url=app.openapi_url, + openapi_url=f"{root_path}{app.openapi_url}", title=app.title + " - ReDoc", - redoc_js_url="/static/redoc.standalone.js", + redoc_js_url=f"{root_path}/static/redoc.standalone.js", ) diff --git a/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py b/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py index cb8e8c224..b197de1f8 100644 --- a/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py +++ b/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py @@ -1,42 +1,91 @@ +import importlib import os from pathlib import Path +from typing import TypedDict import pytest from fastapi.testclient import TestClient -@pytest.fixture(scope="module") -def client(): +class Params(TypedDict): + app_root_path: str + asgi_root_path: str + request_prefix: str + + +@pytest.fixture( + params=[ + Params(app_root_path="", asgi_root_path="", request_prefix=""), + Params(app_root_path="/api", asgi_root_path="", request_prefix="/api"), + Params(app_root_path="/api", asgi_root_path="", request_prefix=""), + Params(app_root_path="", asgi_root_path="/api", request_prefix="/api"), + Params(app_root_path="", asgi_root_path="/api", request_prefix=""), + ], + ids=[ + "Without root_path, request without prefix", + "FastAPI(root_path=root_path), request with prefix", + "FastAPI(root_path=root_path), request without prefix", + "TestClient(root_path=root_path), request with prefix", + "TestClient(root_path=root_path), request without prefix", + ], +) +def params(request: pytest.FixtureRequest): + return request.param + + +@pytest.fixture +def client(params: Params, monkeypatch): static_dir: Path = Path(os.getcwd()) / "static" print(static_dir) static_dir.mkdir(exist_ok=True) - from docs_src.custom_docs_ui.tutorial001 import app + monkeypatch.setenv("ROOT_PATH", params["app_root_path"]) + from docs_src.custom_docs_ui import tutorial001 + + importlib.reload(tutorial001) + app = tutorial001.app - with TestClient(app) as client: + with TestClient(app, root_path=params["asgi_root_path"]) as client: yield client + static_dir.rmdir() -def test_swagger_ui_html(client: TestClient): - response = client.get("/docs") +def test_swagger_ui_html(client: TestClient, params: Params): + request_prefix = params["request_prefix"] + root_path = params["app_root_path"] or params["asgi_root_path"] + + response = client.get(f"{request_prefix}/docs") assert response.status_code == 200, response.text assert "https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js" in response.text assert "https://unpkg.com/swagger-ui-dist@5/swagger-ui.css" in response.text + assert f"{root_path}/docs/oauth2-redirect" in response.text + + response = client.get(f"{request_prefix}/openapi.json") + assert response.status_code == 200 + +def test_swagger_ui_oauth2_redirect_html(client: TestClient, params: Params): + request_prefix = params["request_prefix"] -def test_swagger_ui_oauth2_redirect_html(client: TestClient): - response = client.get("/docs/oauth2-redirect") + response = client.get(f"{request_prefix}/docs/oauth2-redirect") assert response.status_code == 200, response.text assert "window.opener.swaggerUIRedirectOauth2" in response.text -def test_redoc_html(client: TestClient): - response = client.get("/redoc") +def test_redoc_html(client: TestClient, params: Params): + request_prefix = params["request_prefix"] + + response = client.get(f"{request_prefix}/redoc") assert response.status_code == 200, response.text assert "https://unpkg.com/redoc@2/bundles/redoc.standalone.js" in response.text + response = client.get(f"{request_prefix}/openapi.json") + assert response.status_code == 200 + + +def test_api(client: TestClient, params: Params): + request_prefix = params["request_prefix"] -def test_api(client: TestClient): - response = client.get("/users/john") + response = client.get(f"{request_prefix}/users/john") assert response.status_code == 200, response.text assert response.json()["message"] == "Hello john" diff --git a/tests/test_tutorial/test_custom_docs_ui/test_tutorial002.py b/tests/test_tutorial/test_custom_docs_ui/test_tutorial002.py index 712618807..35226b685 100644 --- a/tests/test_tutorial/test_custom_docs_ui/test_tutorial002.py +++ b/tests/test_tutorial/test_custom_docs_ui/test_tutorial002.py @@ -1,42 +1,93 @@ +import importlib import os from pathlib import Path +from typing import TypedDict import pytest from fastapi.testclient import TestClient -@pytest.fixture(scope="module") -def client(): +class Params(TypedDict): + app_root_path: str + asgi_root_path: str + request_prefix: str + + +@pytest.fixture( + params=[ + Params(app_root_path="", asgi_root_path="", request_prefix=""), + Params(app_root_path="/api", asgi_root_path="", request_prefix="/api"), + Params(app_root_path="/api", asgi_root_path="", request_prefix=""), + Params(app_root_path="", asgi_root_path="/api", request_prefix="/api"), + Params(app_root_path="", asgi_root_path="/api", request_prefix=""), + ], + ids=[ + "Without root_path, request without prefix", + "FastAPI(root_path=root_path), request with prefix", + "FastAPI(root_path=root_path), request without prefix", + "TestClient(root_path=root_path), request with prefix", + "TestClient(root_path=root_path), request without prefix", + ], +) +def params(request: pytest.FixtureRequest): + return request.param + + +@pytest.fixture() +def client(params: Params, monkeypatch): static_dir: Path = Path(os.getcwd()) / "static" - print(static_dir) static_dir.mkdir(exist_ok=True) - from docs_src.custom_docs_ui.tutorial002 import app - with TestClient(app) as client: + monkeypatch.setenv("ROOT_PATH", params["app_root_path"]) + from docs_src.custom_docs_ui import tutorial002 + + importlib.reload(tutorial002) + app = tutorial002.app + + with TestClient(app, root_path=params["asgi_root_path"]) as client: yield client + static_dir.rmdir() -def test_swagger_ui_html(client: TestClient): - response = client.get("/docs") +def test_swagger_ui_html(client: TestClient, params: Params): + request_prefix = params["request_prefix"] + root_path = params["app_root_path"] or params["asgi_root_path"] + + response = client.get(f"{request_prefix}/docs") assert response.status_code == 200, response.text - assert "/static/swagger-ui-bundle.js" in response.text - assert "/static/swagger-ui.css" in response.text + assert f"{root_path}/static/swagger-ui-bundle.js" in response.text + assert f"{root_path}/static/swagger-ui.css" in response.text + assert f"{root_path}/docs/oauth2-redirect" in response.text + + response = client.get(f"{request_prefix}/openapi.json") + assert response.status_code == 200 -def test_swagger_ui_oauth2_redirect_html(client: TestClient): - response = client.get("/docs/oauth2-redirect") +def test_swagger_ui_oauth2_redirect_html(client: TestClient, params: Params): + request_prefix = params["request_prefix"] + + response = client.get(f"{request_prefix}/docs/oauth2-redirect") assert response.status_code == 200, response.text assert "window.opener.swaggerUIRedirectOauth2" in response.text -def test_redoc_html(client: TestClient): - response = client.get("/redoc") +def test_redoc_html(client: TestClient, params: Params): + request_prefix = params["request_prefix"] + root_path = params["app_root_path"] or params["asgi_root_path"] + + response = client.get(f"{request_prefix}/redoc") + assert response.status_code == 200, response.text - assert "/static/redoc.standalone.js" in response.text + assert f"{root_path}/static/redoc.standalone.js" in response.text + + response = client.get(f"{request_prefix}/openapi.json") + assert response.status_code == 200 + +def test_api(client: TestClient, params: Params): + request_prefix = params["request_prefix"] -def test_api(client: TestClient): - response = client.get("/users/john") + response = client.get(f"{request_prefix}/users/john") assert response.status_code == 200, response.text assert response.json()["message"] == "Hello john"