尝试在烧瓶中使用简单的rest api和基本的东西。当我尝试介绍数据库时,导入模型失败了
app.py
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
import redis from rq import Queue
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
migrate = Migrate(app, db)
from models import OcrText
models.py
from app import db
class OcrText(db.Model):
# schema
错误
Traceback (most recent call last):
File "app.py", line 21, in <module> from models import OcrText
File "/Users/mid_dev/Learn/Flask/mercari_ml_ocr/models.py", line 1, in <module> from app import db
File "/Users/mid_dev/Learn/Flask/mercari_ml_ocr/app.py", line 21, in <module> from models import OcrText
ImportError: cannot import name 'OcrText'
答案 0 :(得分:1)
是的,您是正确的,这是一个循环导入问题。只需将数据库初始化移至新文件db.py
,然后从app.py
和models.py
导入此文件。这样就可以正常工作。
示例db.py
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
db = None
def init_db(app):
global db
db = SQLAlchemy(app)
Migrate(app, db)
return db
示例app.py
from db import init_db
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
init_db(app)
from models import OcrText
示例models.py
from db import db
class OcrText(db.Model):
# schema