1

I am currently following this pattern to avoid circular imports. This pattern seems to be pretty niche so it's been difficult trying to find a solution googling.

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()

When I run db_create.py separately, I get:

$ 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

What should I do? What is the best pattern to deal with this? I've even tried adding db.create_all() in my application.py after if __name__ == '__main__' but I am still getting the same error

Community
  • 1
  • 1
Tinker
  • 4,165
  • 6
  • 33
  • 72

1 Answers1

3

Tell Flask-SQLAlchemy which is "current" app with app_context

with app.app_context():
    # your code here
    db.create_all()
Raja Simon
  • 10,126
  • 5
  • 43
  • 74