9

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?

3 Answers 3

20

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.

0
15

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

0
6

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='jsmith@google.com')
    db.session.add(admin)
    db.session.commit()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.