1
循環インポートを避けるため、現在this patternに従っています。このパターンはかなりニッチなので、解決策を見つけようとするのは難しいです。Sqlalchemy db.create_all()テーブルを作成していません
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
どうすればよいですか?これに対処する最良のパターンは何ですか?私もif __name__ == '__main__'
後、私application.pyでdb.create_all()
を追加することが、私はまだ