【问题标题】:Why url_for generates URL with localhost as the hostname instead of the domain name?为什么 url_for 生成的 URL 以 localhost 作为主机名而不是域名?
【发布时间】:2022-11-24 01:43:21
【问题描述】:

我有一个使用 Jinja2 模板的 FastAPI Web 应用程序,它在 localhost 上运行良好,但是不是在生产中。问题是没有为 JavaScript 和其他 static 文件正确生成 URL。我已经使用gunicornnginx 将它部署在 EC2 实例上。

我的 HTML 文件中有这行代码:

<script src="{{ url_for('static', path='js/login_signup.js') }}"></script>

问题是它正在生成这样的 URL:

<script src="http://127.0.0.1:8000/static/js/login_signup.js"></script>

我想要的是生成这样的东西:

<script src="http://my_domain.com/static/js/login_signup.js"></script>

【问题讨论】:

  • 可能是因为你没有在0.0.0.0 服务,但你没有给我们任何信息。你是如何启动你的服务器的?

标签: python jinja2 fastapi templating starlette


【解决方案1】:

0.0.0.0而不是127.0.0.1上投放。如果您使用的是uvicorn,这是 FastAPI 的默认 Web 服务器,您需要在启动服务器时传递--host 0.0.0.0。对于其他服务器,请查找等效标志。

【讨论】:

    【解决方案2】:

    选项1

    您可以改用相对路径,如herehere 所述。例子:

    <link href="static/styles.css'" rel="stylesheet">
    

    选项 2

    您可以创建一个自定义函数,在其中替换 URL 中的主机名,然后在您的 Jinja2 模板中使用该函数。如果您还想在 URL 中包含查询参数,而不仅仅是路径参数,请查看 this answerthis answer。例子:

    后端

    from fastapi import FastAPI, Request
    from fastapi.staticfiles import StaticFiles
    from fastapi.templating import Jinja2Templates
    from typing import Any
    import urllib
    
    app = FastAPI()
    
    def my_url_for(request: Request, name: str, **path_params: Any) -> str:
        url = request.url_for(name, **path_params)
        parsed = list(urllib.parse.urlparse(url))
        parsed[1] = 'my_domain.com'
        return urllib.parse.urlunparse(parsed)
        
    
    app.mount('/static', StaticFiles(directory='static'), name='static')
    templates = Jinja2Templates(directory='templates')
    templates.env.globals['my_url_for'] = my_url_for
    

    前端

    <link href="{{ my_url_for(request, 'static', path='/styles.css') }}" rel="stylesheet">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多