Fix /docs endpoint by setting root_path parameter in FastAPI app, by

doing so there's no need to have custom url_for fucntion
This commit is contained in:
Iam54r1n4
2025-02-05 21:25:04 +00:00
parent 82394d6b6c
commit 492719eb3a
5 changed files with 26 additions and 28 deletions

View File

@ -1,28 +1,24 @@
from fastapi import Request
from fastapi.templating import Jinja2Templates
from jinja2 import pass_context
from typing import Any
from starlette.datastructures import URL
from session import SessionStorage, SessionManager
from config import CONFIGS
__TEMPLATES = Jinja2Templates(directory='templates')
# This was a custom url_for function for Jinja2 to add a prefix to the generated URL but we fix the url generation by setting the root path
# @pass_context
# def url_for(context: dict[str, Any], name: str = '', **path_params: dict[str, Any]) -> URL:
# '''
# Custom url_for function for Jinja2 to add a prefix to the generated URL.
# '''
# request: Request = context["request"]
# url = request.url_for(name, **path_params)
# prefixed_path = f"{CONFIGS.ROOT_PATH.rstrip('/')}/{url.path.lstrip('/')}"
@pass_context
def url_for(context: dict[str, Any], name: str = '', **path_params: dict[str, Any]) -> URL:
'''
Custom url_for function for Jinja2 to add a prefix to the generated URL.
'''
request: Request = context["request"]
url = request.url_for(name, **path_params)
prefixed_path = f"{CONFIGS.ROOT_PATH.rstrip('/')}/{url.path.lstrip('/')}"
return url.replace(path=prefixed_path)
# return url.replace(path=prefixed_path)
__TEMPLATES.env.globals['url_for'] = url_for # type: ignore
# __TEMPLATES.env.globals['url_for'] = url_for # type: ignore
def get_templates() -> Jinja2Templates: