'my test python flask app is returning this "partially initialized module 'project' has no attribute 'db' (most likely due to a circular import)"

this is my project directory structure shown in the images with the links below, from my own understanding l am creating a db object in the project directory's init.py file, that object is being imported by models.py please help me understand the nature of the circular import problem and how l can fix it

Folder Structure Images: Folder Structure Project Structure


#traceback

PS Projects\test_app> py .\runServer.pyTraceback (most recent call last):File "C:\Users\Projects\test_app\runServer.py",

 line 1, in \<module\>from project import app 

 File "C:\\Users\\Projects\\test_app\\project_init\_.py", 

 line 4, in \<module\>from .routes import routes 

 File "C:\\Users\\Projects\\test_app\\project\\routes.py", 

 line 3, in \<module\>from project import models

 File "C:\\Users\\Projects\\test_app\\project\\models.py", 

 line 2, in \<module\>from project import db 

 ImportError: cannot import name 'db' from partially initialized module 'project' (most likely due to a circular import)

`

#models-module

from project import db
import uuid

class User(db.Model):  
    id = db.Column(db.String(455), primary_key=True, default=str(uuid.uuid4()))
    name = db.Column(db.String(30))
    surname = db.Column(db.String(30))

#routes-module
from project import models
from flask import Blueprint

routes = Blueprint("routes",__name__)

@routes.route("/")
def index():
    user = models.User(name="Nyasha",surname="Chiza")
    models.db.session.add(user)
    models.db.session.commit()
    return "Landing Page"

@routes.route("/home")
def home():
    user = models.User.query.first()
return 'Welcome {0} {1}'.format(user.name,user.surname)`

#project/__init__.py

from flask import Flask, Blueprint
from flask_sqlalchemy import SQLAlchemy
from .routes import routes
import os

app = Flask(__name__)
db = SQLAlchemy(app)

app.register_blueprint(routes)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///database.db"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")`


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source