Flask问题:通过href访问二级页面返回404错误
Flask项目音频页面链接404问题解决
问题说明
主页面landing.html里的<a href="audio.html">Transcribe Here</a>链接点击后,服务器返回GET /audio.html HTTP/1.1 404错误,尽管audio.html和landing.html处于同一目录下。
相关代码
Python代码
import openai from flask import Flask, render_template # 原代码遗漏该导入,需补充 app = Flask(__name__) app.debug = True #audio_file= open("/path/to/file/audio.mp3", "rb") #transcript = openai.Audio.transcribe("whisper-1", audio_file) @app.route('/') def hello_flask(): return render_template('landing.html') if __name__ == '__main__': app.run()
主页面HTML代码(landing.html)
<html> <head> <title>komodo.ai</title> <link rel="stylesheet" href="static/styles.css"> <meta content="基于AI记录技术,无需手动文档。让你有更多时间做热爱的事,重拾医疗护理的乐趣。" name="description"/> <style> body { text-align: center; } </style> </head> <body> <div class="page-wrapper"> <div class="banner_component"> <h1>欢迎来到我的网页</h1> <p>这是我的网页内容。</p> <!-- 页面其他元素和区块 --> </div> </div> <header> <nav> <ul> <li style="display:inline"><a href="audio.html">前往转录页面</a></li> <li style="display:inline">选项2</li> <li style="display:inline">选项3</li> </ul> </nav> </header> <header> <h1>欢迎来到我们的初创项目</h1> <p>和我们一起探索未来。</p> <a href="/about">了解更多</a> </header> <div id="Komodo image"> <img src="{{ url_for('static', filename='Komodo_image.jpeg') }}"> </div> </body> </html>
问题原因及解决办法
Flask是路由驱动的框架,不会直接读取模板目录下的HTML文件(除非配置静态资源规则,但模板文件不属于静态资源范畴)。当前代码仅给根路径/配置了路由,没有为/audio.html设置对应的路由处理逻辑,所以服务器找不到对应资源,返回404错误。
办法一:添加对应路由和视图函数
在Python代码中新增路由,让服务器能返回audio.html模板:
@app.route('/audio.html') def audio_page(): return render_template('audio.html')
确保audio.html放在Flask默认的templates目录下,和landing.html同级。
办法二:使用Flask规范的路由生成方式(推荐)
这种方式避免硬编码路径,更易维护:
- 调整Python代码的路由命名:
@app.route('/') def landing_page(): return render_template('landing.html') @app.route('/audio') def audio_page(): return render_template('audio.html')
- 修改
landing.html中的链接,用url_for生成正确路径:
<li style="display:inline"><a href="{{ url_for('audio_page') }}">前往转录页面</a></li>
另外注意:原Python代码遗漏了render_template的导入语句,这会导致根路由也无法正常工作,必须补上from flask import Flask, render_template。
内容的提问来源于stack exchange,提问作者user20402884
相关产品推荐
相关产品推荐

