使用Flask-Admin设置模型视图会导致ImportError

时间:2015-05-28 17:56:13

标签: python flask flask-sqlalchemy flask-admin

我正在尝试将用户模型视图添加到Flask-Admin。但是,我得到ImportError: cannot import name db。为什么会发生这种情况?如何解决?

app/__init__.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import flask_admin as admin
from app.models import User

db = SQLAlchemy()
admin = admin.Admin(name="Admin Panel")

def create_app(config_name):
    app = Flask(__name__)
    db.init_app(app)
    admin.init_app(app)
    admin.add_view(ModelView(User, db.session))
    return app

app/models.py

from . import db, login_manager

class User(UserMixin, db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)

当我添加admin.add_view(ModelView(User, db.session))时,我还必须添加from app.models import User。添加以下行后出现此错误:

Traceback (most recent call last):
      File "manage.py", line 3, in <module>
        from app.models import User, Role
      File "/home/qadim/PycharmProjects/esouq/app/__init__.py", line 1, in <module>
        from app.models import User
      File "/home/qadim/PycharmProjects/esouq/app/models.py", line 9, in <module>
        from . import db, login_manager
    ImportError: cannot import name db

1 个答案:

答案 0 :(得分:3)

您的代码在from app.models import User中有__init__.py行。问题是app.modelsfrom . import db。这是循环导入:__init__尝试导入User,尝试导入db,直到__init__尝试导入User后才定义from flask_sqlalchemy import SQLAlchemy from app.models import User db = SQLAlchemy() 。要解决此问题,请将本地应用程序导入移动到所有全局扩展程序的定义之下。

目前,您的代码类似于:

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

from app.models import User

您需要将其更改为:

$ curl -X http://www.hulu.com/bill-hicks-relentless
http://www.hulu.com/watch/768345