【发布时间】: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 路径?
【问题讨论】: