Ich befolge zurzeit this pattern, um zirkuläre Importe zu vermeiden. Dieses Muster scheint ziemlich nisch zu sein, so dass es schwierig war, eine Lösung zu finden, die googelt.Sqlalchemy db.create_all() erstellt keine Tabellen
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()
Wenn ich separat laufen db_create.py, erhalte ich:
$ 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
Was soll ich tun? Was ist das beste Muster, um damit umzugehen? Ich habe sogar versucht, db.create_all()
in meinem application.py nach if __name__ == '__main__'
Zugabe, aber ich bin immer noch die gleichen Fehler