You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask项目中点击链接无法显示hello.html页面问题求助

Flask页面跳转失败问题解决

问题情况

用Flask开发时,main.py里配置了根路由/返回home.html,访问首页一切正常,但home.html里的<a href="hello.html">hello</a>链接点不开,跳转后页面无法显示。

用到的代码

main.py

from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def home():
    return render_template('home.html')

home.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
  <h1>HOME</h1>
  <a href="hello.html">hello</a>
</body>
</html>

hello.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>hello</title>
</head>
<body>
    <h1>Hello</h1>
</body>
</html>

出错原因

Flask是后端框架,不能直接通过HTML文件名访问模板文件。点击hello.html链接时,浏览器会向服务器请求/hello.html路径,但你的main.py里没有配置这个路由对应的处理函数,所以Flask找不到页面,返回404错误。

解决办法

方法1:新增hello路由

在main.py里添加路由代码,让Flask处理/hello请求并返回hello.html模板:

from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def home():
    return render_template('home.html')

# 新增hello路由
@app.route('/hello')
def hello():
    return render_template('hello.html')

同时修改home.html里的链接为路由路径:

<a href="/hello">hello</a>

方法2:用url_for生成链接(更推荐)

Flask提供url_for函数,可根据视图函数名自动生成正确URL,避免硬编码路径:

  1. 修改home.html的链接代码:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
  <h1>HOME</h1>
  <!-- 通过url_for生成hello视图对应的URL -->
  <a href="{{ url_for('hello') }}">hello</a>
</body>
</html>
  1. 确保main.py中存在hello路由(同方法1的新增代码)。

完成上述修改后,点击链接即可正常打开hello页面。

内容的提问来源于stack exchange,提问作者Amal krishna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 10:25:16