creating a database outside the application context
Solution 1:
Flask-SQLAlchemy only needs an app context to operate. You can create an app context manually.
app = create_app(env)
ctx = app.app_context()
ctx.push()
# your code here
ctx.pop()
This is from the docs here and here.
Solution 2:
I know this question has been answered but you can also use the with
statement:
from my_package import create_app
app = create_app(my_envrionment)
with app.app_context():
# your code here
I think this looks a little cleaner :)
Solution 3:
Another elegant way to solve this is using the @with_appcontext decorator.
from flask.cli import with_appcontext
@click.command(name='db-init-data')
@with_appcontext
def db_init_data():
"""Init db with some data"""
admin = User(fname='John', lname='Smith', email='[email protected]')
db.session.add(admin)
db.session.commit()