如何修复 "Module not imported__(Most likely due to circular import error)"

How to fix "Module not imported__(Most likely due to circular import error)"

我遇到了一个问题 My_Directory_Structure app.py

    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    from datetime import datetime
    from users.home import bp
    
    app = Flask(__name__)
    app.register_blueprint(bp, url_prefix="/user")
    
    app.config.from_object(__name__)
    app.config.from_pyfile('myconfig.cfg')
    
    app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///QAEngine.db"
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db = SQLAlchemy(app)
    
    
    class contactform(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(200), nullable=False)
        email = db.Column(db.String(200), nullable=False)
        subject = db.Column(db.String(200), nullable=False)
        message = db.Column(db.String(500), nullable=False)
        date_posted = db.Column(db.DateTime, default=datetime.utcnow)
    
        def __repr__(self) -> str:
            return f"{self.name} = {self.email}"
    
    
    @app.route("/")
    def test():
        return "<h1>This is test message<\h1>"
    
    
    if __name__ == "__main__":
        app.run()

users/home.py

from flask import Blueprint, render_template, request
from app import contactform
from app import db

bp = Blueprint("bp", __name__, static_folder="static",
               template_folder="templates")


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


@bp.route("/contact", methods=['POST', 'GET'])
def contact():
    if request.method == "POST":
        name = request.form['name']
        email = request.form['email']
        subject = request.form['subject']
        message = request.form['message']

        instance = contactform(name=name, email=email,
                               subject=subject, message=message)
        db.session.add(instance)
        db.session.commit()
    return render_template("contact.html")

*我试过了 更改文件相同的文件名 导入 users.home,主页 从 users.home 导入 bp 来自用户。国内进口 * 仍未导入模块并显示

错误
ImportError: cannot import name 'bp' from partially initialized module 'users.home' (most likely due to a circular import) (C:\Users\MUHAMMAD\PycharmProjects\QASystem\users\home.py)?*

您遇到的问题在 Flask 新用户中很常见。有很多方法可以解决它,但最常见的方法是使用 application factory 模式。

简而言之,不要在全球范围内创建 app。您将其创建包装在您在所有导入发生后调用的函数中。