I have an app factory like so
db = SQLAlchemy()
def create_app(environment):
app = Flask(__name__)
app.config.from_object(config[environment])
db.init_app(app)
# ... etc
return app
then, I have a script which fetches CSVs outside of the context of the application. This script is a cron which is run every x hours
I want to update the sqlite database somehow that the application is using. Is this possible?
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.
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 :)
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With