Flask app context for sqlalchemy : <p>I am working on a small rest api in flask. Api has route that registers a request and spawn separate thread to run in background. Here is the code:</p>

<pre><code>def dostuff(scriptname):
    new_thread = threading.Thread(target=executescript,args=(scriptname,))
    new_thread.start()
</code></pre>

<p>Thread starts but it errors out when I try to insert into db from executescript function. It complains about db object not registered with the app.</p>

<p>I am dynamically creating my app (with api as Blueprint).</p>

<p>Here is the structure of the app</p>

<pre><code>-run.py ## runner script
-config
   -development.py
   -prod.py
-app
  -__init__.py
  - auth.py
  - api_v1
     - __init__.py
     - routes.py
     - models.py
</code></pre>

<p>here is my runner script <code>run.py</code> :</p>

<pre><code>from app import create_app, db

if __name__ == '__main__':
    app = create_app(os.environ.get('FLASK_CONFIG', 'development'))
    with app.app_context():
        db.create_all()
    app.run()
</code></pre>

<p>Here is the code from <code>app/__init__.py</code> which creates the app:</p>

<pre><code>from flask import Flask, jsonify, g
from flask.ext.sqlalchemy import SQLAlchemy

db = SQLAlchemy()

def create_app(config_name):
    """Create an application instance."""
    app = Flask(__name__)

    # apply configuration
    cfg = os.path.join(os.getcwd(), 'config', config_name + '.py')
    app.config.from_pyfile(cfg)

    # initialize extensions
    db.init_app(app)
    # register blueprints
    from .api_v1 import api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/api/')
    return app 
</code></pre>

<p>All I need to know is how do I extend app context in <code>routes.py</code>. I can not import app there directly and if I do the following, I get <code>RuntimeError: working outside of application context</code></p>

<pre><code>def executescript(scriptname):
    with current_app.app_context():
        test_run = Testrun(pid=989, exit_status=988,comments="Test TestStarted")
        db.session.add(test_run)
        db.session.commit()
</code></pre>
