gpt4 book ai didi

python - Sqlalchemy db.create_all() 不创建表

转载 作者:行者123 更新时间:2023-12-01 03:56:09 25 4
gpt4 key购买 nike

我目前正在关注this pattern以避免循环进口。这种模式似乎相当小众,因此很难通过谷歌搜索找到解决方案。

模型.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

应用程序.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

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

最佳答案

使用 app_context 告诉 Flask-SQLAlchemy 这是“当前”应用程序

with app.app_context():
# your code here
db.create_all()

关于python - Sqlalchemy db.create_all() 不创建表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37427646/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com