【问题标题】:How to render static url_for paths when using app.app_context()使用 app.app_context() 时如何呈现静态 url_for 路径
【发布时间】:2020-05-22 13:45:27
【问题描述】:

我正在尝试创建一个简单的脚本来从基本的 Flask 应用程序生成静态页面。为此,我通过 app.app_context() 呈现视图。但是,这需要设置 SERVER_NAME 配置。这会在渲染后生成完整的而不是静态的 url 路径。

from flask import Flask, render_template

app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(24)
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config['SERVER_NAME'] ='localhost:5000'

@app.route('/', methods=['GET'])
def index():
    return render_template('index.html')

@app.route('/about', methods=['GET'])
def about():
    return render_template('about.html')

if __name__ == '__main__':
    with app.app_context():
        view_functions = app.view_functions
        for key, value in view_functions.items():
            if key is not 'static':
                html = render_template(f'{key}.html')
                with open(f'{key}.html'), mode='w') as file:
                    file.write(html)

现在,在 HTML 文件中,我使用 url_for 来呈现这样的 url 路径:

<a class="nav-link" href="{{ url_for('about') }}">About</a>

渲染后,我期望静态 url 路径:

# Expected: 
<a class="nav-link" href="/about">About</a>

# Reality:
<a class="nav-link" href="http://localhost:5000/about">About</a>

有没有办法在使用 app_context 时呈现静态而不是完整的 url 路径?

【问题讨论】:

    标签: python flask


    【解决方案1】:

    _external=False 添加到 url_for:

    <a class="nav-link" href="{{ url_for('about', _external=False) }}">About</a>
    

    如果您正在为电子邮件呈现链接,则相反,例如,您希望将 _external 设置为 True。

    【讨论】:

    • 谢谢,这确实有效。事实证明,我需要 '/about.html' 而不是 '/about'。是否可以在 url_for() 调用中呈现 html 文件扩展名?
    • 不,你不需要,因为你可以使用 Jinja 的语法 {% include "/path/to/template.html" %}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 2011-06-06
    • 2019-07-02
    相关资源
    最近更新 更多