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

Flask项目访问出现404错误,请求问题排查与解决

Flask项目访问404错误排查与解决方法

问题现象

执行python app.py启动Flask项目后,访问页面时出现404 Not Found错误,错误提示:

The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

已编写包含订单管理API的Flask后端代码,并在templates目录中放置了需要访问的index.html文件。

核心原因

当前Flask后端代码仅配置了订单相关的API路由(/orders、/order/update/<int:order_id>、/order/create),缺少指向首页(index.html)的路由配置,导致访问根路径(/)时服务器找不到对应的处理逻辑。

排查步骤

  • 检查路由定义:核对后端代码的路由列表,确认是否存在返回页面的路由(如根路径/)。
  • 确认模板目录结构:确保index.html存放在项目根目录下的templates文件夹中(Flask默认模板查找路径)。
  • 验证模板渲染逻辑:确认是否调用了render_template函数来返回HTML模板文件。

解决方法

在Flask后端代码中添加根路由,用于渲染index.html:

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

将上述代码添加到现有路由之后、启动代码之前,示例位置如下:

@app.route('/order/create', methods=['POST'])
def create_order():
    data = request.json
    new_order = Order(status=data['status'], current_process=data['current_process'], unique_code=data['unique_code'])
    db.session.add(new_order)
    db.session.commit()
    return jsonify({'message': 'Order created'})

# 添加根路由
@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)

额外优化(可选)

原代码中使用的@app.before_first_request装饰器在Flask 2.0及以上版本已被弃用,可替换为启动时手动创建数据库表的逻辑,避免运行警告:

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(debug=True)

内容的提问来源于stack exchange,提问作者Chris fw

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 04:53:13