Python 在 Flask 中按文件分离 SQLAlchemy 模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14789668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Separate SQLAlchemy models by file in Flask
提问by element119
Many examples for Flask apps that I have seen have the models stored directly in the main app file (http://pythonhosted.org/Flask-SQLAlchemy/quickstart.html, http://maximebf.com/blog/2012/10/building-websites-in-python-with-flask/). Other ones (http://flask.pocoo.org/docs/patterns/sqlalchemy/) have a "models.py" file in which models are placed.
我见过的许多 Flask 应用程序示例都将模型直接存储在主应用程序文件中(http://pythonhosted.org/Flask-SQLAlchemy/quickstart.html、http://maximebf.com/blog/2012/10/ building-websites-in-python-with-flask/)。其他(http://flask.pocoo.org/docs/patterns/sqlalchemy/)有一个“models.py”文件,其中放置了模型。
How can I have my Flask app import models from separate files, e.x. "User.py"? When I try creating a User.py file with these contents:
如何让我的 Flask 应用程序从单独的文件(例如“User.py”)导入模型?当我尝试使用以下内容创建 User.py 文件时:
from app import db
class User(db.Model):
[...]
I get the following error:
我收到以下错误:
File "/Users/stackoverflow/myapp/models/User.py", line 1, in <module>
from app import db
ImportError: No module named app
When I insert from models import Userin my module file.
当我插入from models import User我的模块文件时。
采纳答案by element119
This answer was extremely helpful: https://stackoverflow.com/a/9695045/353878.
这个答案非常有帮助:https: //stackoverflow.com/a/9695045/353878。
I needed to not initialize the db right away.
我不需要立即初始化数据库。
回答by Redian
from app.database import Base
class User(Base):
__tablename__ = 'users'
Shouldn it be this way ??
应该是这样??

