corvid
corvid

Reputation: 11197

creating a database outside the application context

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?

Upvotes: 9

Views: 6235

Answers (3)

olive_tree
olive_tree

Reputation: 1457

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

Upvotes: 6

davidism
davidism

Reputation: 127310

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.

Upvotes: 20

Joe Doherty
Joe Doherty

Reputation: 3958

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

Upvotes: 15

Related Questions