使用Application Factory实现Flask-WhooshAlchemy

时间:2014-05-03 23:28:59

标签: python python-2.7 flask flask-sqlalchemy

如果应用程序是在全局范围内创建的

__初始化__。PY

from flask import Flask

app = Flask(__name__)
app.config.from_object('config')
from app import views

在run.py下面的这段代码将开始使用{strong> views.py 中的whoosh_search,例如post = Post.query.whoosh_search(name, limit=3).all(

run.py

import os
from app import app


from flask.ext.script import Manager
from flask.ext.moment import Moment

from flask.ext.sqlalchemy import SQLAlchemy
import flask.ext.whooshalchemy as whooshalchemy


basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] =\
    'sqlite:///' + os.path.join(basedir, 'post.sqlite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SECRET_KEY'] = 'hard to guess string'

db = SQLAlchemy(app)

manager = Manager(app)
moment = Moment(app)

class Post(db.Model):
    __tablename__ = 'post'
    __searchable__ = ['body']
    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.String(140))
    timestamp = db.Column(db.DateTime))

    def __repr__(self):
        return '<Post %r>' % (self.body)

whooshalchemy.whoosh_index(app, Post)

if __name__ == '__main__':
    db.create_all()
    manager.run()

了解如何使用Flask-WhooshAlchemy实现Application Factory

__初始化__。PY

from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from config import config

bootstrap = Bootstrap()
moment = Moment()
db = SQLAlchemy()

def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    bootstrap.init_app(app)
    moment.init_app(app)
    db.init_app(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    return app

如何在app中使用应用程序工厂注册whooshalchemy.whoosh_index(app, Post),以便在{strong> views.py 中使用whoosh_search,就像在上一个示例中一样。

1 个答案:

答案 0 :(得分:0)

在您的应用程序工厂函数fx中。初始化所有应用程序之后,以及注册蓝图之前。您应该导入模型并运行whoosh_index。有点像:

  from .model import Post
  whooshalchemy.whoosh_index(app, Post)