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

Time:10-13

I am a beginner in Flask and facing an issue 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")

*I tried changing the file same file name Import users.home, home from users.home import bp from users. home import * Still module not imported and showing an error that

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)?*

CodePudding user response:

The issue you are having is common among new Flask users. There are many ways to address it but the most common one is to use an application factory pattern.

In short, instead of creating your app globally. You wrap its creation inside a function that you call after all imports have occurred.

  • Related