我正在尝试从我的models.py导入一个类,但是我认为我遇到了循环导入问题。我不确定该如何解决。
我尝试移动导入,并更改每个文件中的导入。
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 (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'
答案 0 :(得分:0)
您需要避免循环导入。在您的app.py
中,为什么需要从模型中导入任何内容?
# 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()
如果最终需要使用app.py
中的模型或需要解决其他循环导入问题,通常可以避免延迟加载,直到实际调用方法/函数为止。
@app.route('/')
def main():
"""
For example, if you need to reference SleepResult here...
"""
from models import SleepResult
return SleepResult.query.all()