Initialize a Flask-WhooshAlchemy index when using the app factory pattern
<p>I am developing an app with Flask using the <a href="http://flask.pocoo.org/docs/0.11/patterns/appfactories/#factories-extensions" rel="nofollow">application factory pattern</a>. Initializing the Whoosh index doesn't work, because <code>current_app</code> cannot be used without setting up an app context explicitly. How do I do this?</p>

<p><code>__init__.py</code></p>

<pre><code>from flask import Flask
from .frontend import frontend

def create_app(configfile=None):
    app = Flask(__name__)

    from .models import db
    db.init_app(app)

    app.register_blueprint(frontend)

    return app
</code></pre>

<p><code>models.py</code></p>

<pre><code>from flask_sqlalchemy import SQLAlchemy
import flask_whooshalchemy as wa
from flask import current_app

db = SQLAlchemy()

class Institution(db.Model):
    __searchable__ = ['name', 'description']
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(40))
    description = db.Column(db.Text)

# this does not work
wa.whoosh_index(current_app, Institution)
</code></pre>

<p><a href="http://stackoverflow.com/questions/19437883/when-scattering-flask-models-runtimeerror-application-not-registered-on-db-w">You can't use <code>current_app</code> outside an application context.</a>  An application context exists during a request, or when explicitly created with <code>app.app_context()</code>.</p>

<p>Import your models during <code>create_app</code> and index them with Whoosh there.  Remember, the factory is where you're performing all setup for the application.</p>

<pre><code>def create_app():
    app = Flask('myapp')
    ...
    from myapp.models import Institution
    wa.whoosh_index(app, Institution)
    ...
    return app
</code></pre>

<p>If you want to keep the code local to the blueprint, you can use the blueprint's <code>record_once</code> function to perform the index when the blueprint is registered on the app.</p>

<pre><code>@bp.record_once
def record_once(state):
    wa.whoosh_index(state.app, Institution)
</code></pre>

<p>This will be called at most once when registering the blueprint with an app.  <code>state</code> contains the app, so you don't need the <code>current_app</code>.</p>

python flask