I'm using the ASGI sites beta, but I'm having some route-related problems when using FastAPI's url_for
(which is actually Starlette's), here is a MWE using it to create a link to a second page:
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
app = FastAPI()
@app.get("/", response_class=HTMLResponse)
async def main_page(request: Request):
other_url = request.url_for("other_page")
html_content = f"""
<html>
<head>
<title>Main Page</title>
</head>
<body>
<h1>Welcome to the Main Page</h1>
<p>Click <a href="{other_url}">here</a> to go to the Other Page.</p>
</body>
</html>
"""
return HTMLResponse(content=html_content)
@app.get("/other", response_class=HTMLResponse)
async def other_page():
html_content = """
<html>
<head>
<title>Other Page</title>
</head>
<body>
<h1>This is the Other Page</h1>
<p>You have successfully navigated to the other page.</p>
</body>
</html>
"""
return HTMLResponse(content=html_content)
When I run it in my machine with uvicorn --host HOSTNAME test:app
, url_for
uses the provided hostname. However, in PythonAnywhere, despite adding --host USERNAME.pythonanywhere.com
to the launching command, url_for
references "localhost".
I guess uvicorn is running behind Nginx, so perhaps it could be related to its configuration (see here), but I think I have no access to it. Again, running with --host USERNAME.pythonanywhere.com --proxy-headers --forwarded-allow-ips="*"
did not solve the problem.
Although I know there are workarounds like using relative routes or writing a custom function (see here), I think this affects existing software. For example, I've also tried mounting a gradio app in FastAPI and the endpoint redirects to localhost, so I guess the problem is the same.
Any ideas?