Flask动态路由问题:根路径'/'匹配失败导致404错误
Flask根路径404问题解决
你的代码里没有为根路径'/'定义路由处理函数,当前的动态路由@app.route('/<string:page_name>')仅匹配包含路径参数的URL(比如/about),无法匹配空的根路径请求,因此访问/时返回404错误。
另外代码里还有几处小问题需要修正:
- 导入语句末尾多了逗号,会导致语法错误
- 未导入
send_from_directory和os模块,favicon函数无法正常运行 - 动态路由函数的注释多了一个单引号
以下是修正后的完整代码:
from flask import Flask, render_template, send_from_directory import os app = Flask(__name__) @app.route('/favicon.ico') def favicon(): '''返回网站图标''' return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico', mimetype='image/vnd.microsoft.icon') @app.route('/') def home(): '''处理根路径请求,返回首页模板''' return render_template('index.html') # 替换为你实际的首页模板文件名 @app.route('/<string:page_name>') def html_page(page_name): '''模板页面的动态路由''' return render_template(page_name)
关键改动说明:
- 添加
@app.route('/')路由,指定根路径对应的处理函数,返回你的首页模板(比如index.html) - 补全缺失的模块导入,修正语法错误
- 清理多余的注释符号
这样访问根路径/时,就会正常渲染首页模板,其他带路径参数的URL仍通过动态路由处理。
内容的提问来源于stack exchange,提问作者brucecarlon
相关产品推荐
相关产品推荐

