Flask:href链接到html不工作

2024-04-26 07:54:20 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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')

您好.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>

路径1.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时,它可以正常工作。 而且,当在新选项卡中打开时,它也可以正常工作。 我需要帮助!!! 谢谢您!!!


Tags: fromimportapplocalhostflaskreturntitledef
1条回答
网友
1楼 · 发布于 2024-04-26 07:54:20

你应该使用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为你制作网址。。。

*你好像忘了链接处的斜杠。 应为本地主机:8080/路由/ 但是使用url更好,因为它避免了这类问题

相关问题 更多 >