Python Sqlalchemy db.create_all()不创建表
我目前正在遵循,以避免循环进口。这种模式似乎非常适合,所以很难在谷歌上找到解决方案 models.pyPython Sqlalchemy db.create_all()不创建表,python,flask,sqlalchemy,Python,Flask,Sqlalchemy,我目前正在遵循,以避免循环进口。这种模式似乎非常适合,所以很难在谷歌上找到解决方案 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")
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
$python db_create.py
回溯(最近一次呼叫最后一次):
文件“db_create.py”,第6行,在
db.create_all()
文件“/home/ubuntu/.virtualenvs/paw-py/local/lib/python2.7/site-packages/flask\u-sqlalchemy/\uu_-init\u__;.py”,第972行,在create\u-all中
self.\u为所有表执行(应用程序、绑定、“创建所有表”)
文件“/home/ubuntu/.virtualenvs/paw-py/local/lib/python2.7/site-packages/flask\u-sqlalchemy/\uuuuuuuu-init\uuuuuuuuuuu.py”,第949行,针对所有表执行
app=self.get\u app(app)
文件“/home/ubuntu/.virtualenvs/paw-py/local/lib/python2.7/site-packages/flask\u-sqlalchemy/\u_-init\u_.py”,第922行,在get\u应用程序中
raise RUNTIMERROR('应用程序未在数据库上注册'
RuntimeError:应用程序未在db实例上注册,并且没有绑定到当前上下文的应用程序
我应该怎么做?处理这个问题的最佳模式是什么?我甚至尝试过在
之后添加db.create_all()
,如果uu name_uuuu=='uu main_uuu'
的话,在之后添加db.create_uall()
,但是我仍然会遇到同样的错误告诉Flask SQLAlchemy,这是一个具有应用程序上下文的“当前”应用程序
with app.app_context():
# your code here
db.create_all()