【问题标题】:FastAPI links created by url_for in Jinja2 template use HTTP instead of HTTPSJinja2 模板中 url_for 创建的 FastAPI 链接使用 HTTP 而不是 HTTPS
【发布时间】:2021-12-29 15:53:13
【问题描述】:

我将服务员提供的 Flask 中的应用程序迁移到 uvicorn 提供的 FastAPI,但我无法强制链接(由 index.html 模板中的 url_for 生成)使用 HTTPS 而不是 HTTP。

和我用过的女服务员:

from waitress import serve
import flask_app

PORT=5000
HOST_IP_ADDRESS='0.0.0.0'

serve(flask_app.app, host=HOST_IP_ADDRESS, port=PORT, url_scheme="https")

我尝试使用 uvicorn 使用 proxy_headers,但这没有用。我在 index.html 中使用了一种解决方法

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">

从静态文件正确加载 style.css,但到另一个端点的链接仍然使用 HTTP。

有没有一种简单的方法可以强制 url_for 创建的所有链接都使用 HTTPS?

【问题讨论】:

    标签: https jinja2 fastapi uvicorn


    【解决方案1】:

    我之前也遇到过这个问题。一种可能的解决方案是创建一个自定义的url_for 函数来更改协议,然后将其添加到 Jinja 环境中。一种可能的实现可能如下所示:

    template = Jinja2Templates("/path/to/templates")
    
    def https_url_for(request: Request, name: str, **path_params: Any) -> str:
    
        http_url = request.url_for(name, **path_params)
    
        # Replace 'http' with 'https'
        return http_url.replace("http", "https", 1)
    
    template.env.globals["https_url_for"] = https_url_for
    

    您必须将请求传递给该函数,以便它知道如何生成url_for,但无论哪种方式都应将请求传递给您的 Jinja2 模板。

    然后您可以像这样在 Jinja2 模板中使用它:

    https_url_for(request, "/https/path", search="hi")
    

    生成的网址应类似于https://&lt;domain&gt;/https/path?search=hi

    【讨论】:

    • 完美,这种解决方法对我有用。只是为了完成最终代码:我在 jinja 中有url_for('fastapi_function_name', kwarg1='something', kwarg2='somethingelse') 格式的链接。我将其修改为您的 https_url_for 函数并将请求添加为第一个参数:https_url_for(request, 'fastapi_function_name', kwarg1='something', kwarg2='somethingelse')。 html 中的样式表和图像仍然保持不变:{{ url_for('static', path='css/style.css') }} if app.mount("/static", StaticFiles(directory="static"), name="static") 和图像相同
    猜你喜欢
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 2013-01-26
    • 2014-08-12
    • 1970-01-01
    • 2019-05-29
    • 1970-01-01
    • 2012-06-22
    相关资源
    最近更新 更多