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

Flask应用工厂设置后出现ImportError的原因及解决方法问询

Flask应用工厂模式下ImportError问题解决

错误原因

  • 模块未导出app变量:app/__init__.py仅在init_app()函数内部定义了Flask实例app,未在模块级别暴露该变量,导致routes.py中from app import app无法找到目标。
  • 循环导入隐患:即便强行在__init__.py定义模块级app,也会触发循环导入——init_app()导入routes,routes又导入app,打乱初始化顺序。

修改方案(推荐使用蓝图,符合官方最佳实践)

1. 调整app/__init__.py

添加蓝图注册逻辑,保持应用工厂结构:

from flask import Flask
from .routes import bp as main_bp

def init_app():
    """Initialize the core app"""
    app = Flask(__name__, instance_relative_config=False)
    app.config.from_object("config.Config")

    with app.app_context():
        app.register_blueprint(main_bp)
        return app

2. 重构app/routes.py

改用蓝图替代直接导入app:

from flask import render_template, Blueprint
from app.forms import ContactForm

# 创建名为main的蓝图
bp = Blueprint('main', __name__)

@bp.route("/")
def index():
    title = "Welcome to Project"
    return render_template("hero-page.html", title=title)

@bp.route("/gallery/")
def gallery():
    return render_template("gallery.html")

@bp.route("/about-us/")
def about_us():
    return render_template("about-us.html")

3. 确认server.py内容

确保通过应用工厂创建实例:

from app import init_app

app = init_app()

if __name__ == "__main__":
    app.run()

备选方案(无蓝图实现)

若暂不使用蓝图,可通过路由注册函数调整逻辑:

修改app/routes.py

from flask import render_template
from app.forms import ContactForm

def register_routes(app):
    @app.route("/")
    def index():
        title = "Welcome to Project"
        return render_template("hero-page.html", title=title)

    @app.route("/gallery/")
    def gallery():
        return render_template("gallery.html")

    @app.route("/about-us/")
    def about_us():
        return render_template("about-us.html")

修改app/__init__.py

from flask import Flask

def init_app():
    """Initialize the core app"""
    app = Flask(__name__, instance_relative_config=False)
    app.config.from_object("config.Config")

    with app.app_context():
        from .routes import register_routes
        register_routes(app)
        return app

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 12:12:06