Sqlalchemy db.create_all()没有创建表

时间:2016-05-25 04:05:57

标签: python flask sqlalchemy

我目前正在关注this pattern以避免循环导入。这种模式似乎是非常小众,所以很难找到一个解决方案谷歌搜索。

models.py

from sqlalchemy.orm import relationship

db = SQLAlchemy()

class Choice(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  text = db.Column(db.String(32))
  votes = relationship("Vote")

  def __init__(self, text):
    self.text = text

application.py

app = Flask(__name__)
app.debug = True

basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'db.sqlite3')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)      # Reinitialiez db.Model to avoid cyclical imports in models.py

db_create.py

#!flask/bin/python
from application import app, db
from models import Choice

db.init_app(app)
db.create_all()

db.session.add(Choice("Red"))
db.session.add(Choice("Blue"))
db.session.add(Choice("Green"))

db.session.commit()

当我单独运行db_create.py时,我得到:

$ python db_create.py
Traceback (most recent call last):
  File "db_create.py", line 6, in <module>
    db.create_all()
  File "/home/ubuntu/.virtualenvs/paw-py/local/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 972, in create_all
    self._execute_for_all_tables(app, bind, 'create_all')
  File "/home/ubuntu/.virtualenvs/paw-py/local/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 949, in _execute_for_all_tables
    app = self.get_app(app)
  File "/home/ubuntu/.virtualenvs/paw-py/local/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 922, in get_app
    raise RuntimeError('application not registered on db '
RuntimeError: application not registered on db instance and no application bound to current context

我该怎么办?处理这个问题的最佳模式是什么?我甚至尝试在db.create_all()后的application.py中添加if __name__ == '__main__',但我仍然遇到同样的错误

1 个答案:

答案 0 :(得分:2)

使用app_context

告诉Flask-SQLAlchemy这是“当前”的应用程序
with app.app_context():
    # your code here
    db.create_all()