2
votes

I'm trying to import a class from my models.py, but I think I'm running into a circular import issue. I'm not sure how to resolve this.

I've tried moving the import, and changing imports in each file.

app.py:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
# import psycopg2
import os

# Init app
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))


#SQLlite DATABASE
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///sleepTracker.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['DEBUG'] = True

# Init db
db = SQLAlchemy(app)

from models import SleepResult

@app.route('/')
def main():
    return 'Hello World!'

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

models.py:

from manage import db, app

class SleepResult(db.Model):
    __tablename__ = 'sleep_result'
    sleep_result_id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer)
    sleep_result = db.Column(db.Integer)

    def __init__(self,user_id, sleep_result):
        self.user_id = user_id
        self.sleep_result = sleep_result

    def __repr__(self):
        return '<SleepTracker {}>'.format(self.sleep_result)

manage.py:

from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand

from app import app, db

migrate = Migrate(app, db)

manager = Manager(app)
manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()

traceback:

Traceback (most recent call last):
  File "app.py", line 19, in <module>
    from models import SleepResult
  File "/home/john/Documents/sleep_tracker/models.py", line 1, in <module>
    from manage import db, app
  File "/home/john/Documents/sleep_tracker/manage.py", line 4, in <module>
    from app import app, db
  File "/home/john/Documents/sleep_tracker/app.py", line 19, in <module>
    from models import SleepResult
ImportError: cannot import name 'SleepResult'
1
Yes, IMO it's a circular import, comment out L19 in app.py should workMark Mikofski
@SuperShoot I tried that, same error. I'm following this guide, and I think I've matched it completely, but no dice. gist.github.com/mayukh18/2223bc8fc152631205abd7cbf1efdd41rjb
Yep, I've copied that code exactly as presented and run into the same issue as you. You should look at the official docs for a good example of how to structure your application: flask.palletsprojects.com/en/1.1.x/tutorial/factory/…SuperShoot

1 Answers

0
votes

You'll need to avoid circular imports. In your app.py why do you need to import anything from models?

# Init db
db = SQLAlchemy(app)

# Why do you need this here?
# from models import SleepResult

@app.route('/')
def main():
    return 'Hello World!'

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

If you end up needing to models in app.py or need to work around other circular imports, you typically can get away with deferring loading until the method/function is actually called.

@app.route('/')
def main():
    """
    For example, if you need to reference SleepResult here...
    """
    from models import SleepResult


    return SleepResult.query.all()