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

Flask路由返回404错误:URL短链项目多环境配置问题排查

问题解决:Flask端点返回404的原因及修复方案

问题根源

你的代码里存在两个独立的Flask实例:

  • routes.py中通过app = create_app()创建了一个本地Flask实例,并在这个实例上注册了/encode和/decode路由
  • 但实际运行的是app.py或Gunicorn启动的、由create_app("config.ProductionConfig")生成的另一个Flask实例

这两个实例完全独立,运行时的实例根本没有注册任何路由,所以访问时返回404。

修复方案(两种可选)

方案1:在工厂函数中直接注册路由

适合小型项目,修改步骤如下:

  1. 修改routes.py:删除本地创建的app实例,仅保留视图函数
from flask import request, jsonify

def encode():
    """Endpoint that encodes a URL to a shortened URL."""
    # 补充业务逻辑,示例返回:
    return jsonify({"status": "success", "message": "Encode endpoint is working"}), 200

def decode(short_code):
    """Endpoint that decodes a shortened URL to its original URL."""
    # 补充业务逻辑,示例返回:
    return jsonify({"status": "success", "short_code": short_code, "original_url": "https://example.com"}), 200
  1. 修改tinyURL/__init__.py:在create_app函数中导入视图并注册路由
from flask import Flask

def create_app(config_class='config.DevelopmentConfig'):
    app = Flask(__name__)
    app.config.from_object(config_class)
    
    # 导入视图函数并注册到当前app实例
    from tinyURL.routes import encode, decode
    app.add_url_rule('/encode', view_func=encode, methods=['POST'])
    app.add_url_rule('/decode/<short_code>', view_func=decode, methods=['GET'])
    
    return app

方案2:使用Flask蓝图(推荐大型项目)

蓝图更适合模块化管理路由,修改步骤如下:

  1. 修改routes.py:创建蓝图并在蓝图上注册路由
from flask import Blueprint, request, jsonify

# 创建蓝图实例
bp = Blueprint('shortener', __name__)

@bp.route('/encode', methods=['POST'])
def encode():
    """Endpoint that encodes a URL to a shortened URL."""
    return jsonify({"status": "success", "message": "Encode endpoint is working"}), 200

@bp.route('/decode/<short_code>', methods=['GET'])
def decode(short_code):
    """Endpoint that decodes a shortened URL to its original URL."""
    return jsonify({"status": "success", "short_code": short_code, "original_url": "https://example.com"}), 200
  1. 修改tinyURL/__init__.py:在create_app函数中注册蓝图
from flask import Flask

def create_app(config_class='config.DevelopmentConfig'):
    app = Flask(__name__)
    app.config.from_object(config_class)
    
    # 导入蓝图并注册到当前app实例
    from tinyURL.routes import bp
    app.register_blueprint(bp)
    
    return app

验证修复

  • 运行python app.py,访问POST /encode或GET /decode/test,会返回正常的JSON响应
  • 执行gunicorn-starter.sh,同样可以正常访问端点

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 19:03:30