简体   繁体   English

Python、Flask、SQLAlchemy:无法从模型导入

[英]Python, Flask, SQLAlchemy: cannot import from models

I've got a weird problem.我有一个奇怪的问题。

I am building a Flask app with SQLAlchemy.我正在使用 SQLAlchemy 构建 Flask 应用程序。 I have a file with models, namely, models.py.我有一个包含模型的文件,即models.py。 And I have a User model there.我在那里有一个 User 模型。

If I open my "views.py" and insert a string如果我打开我的“views.py”并插入一个字符串

import models

and then use the User model like然后使用 User 模型,如

u=models.User.query.filter_by(name='John',password='Doe').first()

everything works fine.一切正常。

But if instead of "import models" i put但是如果不是“导入模型”,我把

from models import User

Python crashes and says: Python 崩溃并说:

ImportError: cannot import name User

how can this be possible?这怎么可能?

you most likely have a circular import;你很可能有一个循环导入; your, lets say 'app' module:你的,让我们说“应用程序”模块:

# app.py
import models
...

def doSomething():
    models.User....

but your models module also imports app但是您的models模块也导入了app

import app

class User:
    ...

since models imports app , and app imports models , python has not finished importing models at the point app tries to import models.User ;由于models导入appapp导入models ,因此在app尝试导入models.User ,python 还没有完成导入models the User class has not been defined (yet). User类尚未定义(尚未)。 Either break the cyclic import (make sure models doesn't import anything that also imports models ), or you'll just have to make do with models.User instead of the shorter User in app .要么打破循环导入(确保models不导入任何也导入models东西),或者你只需​​要使用models.User而不是app较短的User

Instead of代替

from models import User

use

from models import *

在这种情况下,您将模型导入到views.py因此如果您需要模型中的类,请从views.py导入它,循环导入问题将得到解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM