Forums

ImportError: cannot import name 'db' from partially initialized module 'flask_app'

Hello...

The following error is driving me crazy... I'm trying to do, what should be a simple tutorial and I keep receiving the following error:

2024-10-06 06:32:54,271: Error running WSGI application
2024-10-06 06:32:54,271: ImportError: cannot import name 'db' from partially initialized 
module 'flask_app' (most likely due to a circular import) 
(/home/kpuln/mysite/flask_app.py)
 2024-10-06 06:32:54,272:   File "/var/www/kpuln_pythonanywhere_com_wsgi.py", line 16, in <module>
2024-10-06 06:32:54,272:     from flask_app import app as application  # noqa
2024-10-06 06:32:54,272: 
2024-10-06 06:32:54,272:   File "/home/kpuln/mysite/flask_app.py", line 18, in <module>
2024-10-06 06:32:54,272:     from model import User
2024-10-06 06:32:54,272: 
2024-10-06 06:32:54,272:   File "/home/kpuln/mysite/model.py", line 2, in <module>
2024-10-06 06:32:54,272:     from flask_app import db
2024-10-06 06:32:54,273: ***************************************************
2024-10-06 06:32:54,273: If you're seeing an import error and don't know why,
2024-10-06 06:32:54,273: we have a dedicated help page to help you debug: 
2024-10-06 06:32:54,273: https://help.pythonanywhere.com/pages/DebuggingImportError/
2024-10-06 06:32:54,273: ***************************************************

The following is the code snippet from my model.py file:

from . import db
from flask_login import UserMixin
class User(UserMixin, db.Model):
      id         = db.Column(db.Integer, primary_key=True)  # primary_key
     email       = db.Column(db.String(255), unique=True)

The following is a snippet from the init.py file.

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager

db = SQLAlchemy()

The error seems to be complaining about "db" being imported from the init.py file. I've tried

from myapp import db

and that has not worked either.

Any suggestions ..?

You may have a circular import (that is where one module imports from another module that also imports from the first module - though there could be multiple steps in between).

In your case, it's because flask_app imports from model and then model in turn imports from flask_app again. You best bet is probably to place db in its own module so that flask_app and model can import that without there being a circular import.

Wow.... That worked... Thank you.. I really appreciate it....

Here is what I did...

I created a file db_file.py with the following as its contents

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

Then in my model.py file, I added

from db_file import db

Again... Thanks for that suggestion..

Glad to hear that you made it work.