Flask:HTML中的href链接无法工作

4
我有一个基本的Flask应用程序,其结构如下 :

from flask import Flask
from flask import render_template
app = Flask(__name__,template_folder='E:\Programming\Python Projects\Flask')

@app.route('/')
def index():
    return render_template('hello.html')
@app.route('/route/')
def route1():
    return render_template('route1.html')
app.run(debug = True,port = 8080,host = '0.0.0.0')

hello.html:

<!DOCTYPE html>
<html>
<head>
    <title>Rendered!!</title>
</head>
<body>
<h1>
    The template has been rendered!!!<br>
    <a href="localhost:8080/route">Route No. 1</a>
</h1>
</body>
</html>

route1.html :

<!DOCTYPE html>
<html>
<head>
    <title>Route No. 1</title>
</head>
<body>
<h2>
    This is the first route!!!<br>
    Hello World!!!
</h2>
<iframe src="https://www.youtube.com/embed/YQHsXMglC9A" width="853" height="480" frameborder="0" allowfullscreen></iframe>
</body>
</html>

当我打开 localhost:8080 时,它能正常工作。 但是当我点击链接时,它会显示:
The address wasn’t understood
Firefox doesn’t know how to open this address, because one of the following protocols (localhost) isn’t associated with any program or is not allowed in this context.

当我手动在地址栏输入localhost:8080/route时,它可以正常工作。 同时,在新标签页中打开也可以正常工作。 我需要帮助!!! 谢谢!!!


1
你能否尝试将链接更改为相对路径 /route,而不是绝对路径?或者你可以添加 http:// 作为前缀,使链接变成 http://localhost:8080/route - abagshaw
1个回答

5
您应该使用 from flask import render_template, url_for,并在模板中这样写:
<h1>
The template has been rendered!!!<br>
<a href="{{ url_for('route1') }}">Route No. 1</a>
</h1>

让Flask和Jinja2帮你生成URL链接...

*看起来你忘记在链接后面添加斜杠了。 应该是localhost:8080/route/ 但最好使用url_for,因为它可以避免这种问题


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接