Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 423
corvid Avatar asked Jun 05 '14 12:06

corvid


3 Answers

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.

like image 71
davidism Avatar answered Nov 08 '22 21:11

davidism


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

like image 33
Joe Doherty Avatar answered Nov 08 '22 20:11

Joe Doherty


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()
like image 5
olive_tree Avatar answered Nov 08 '22 19:11

olive_tree