gpt4 book ai didi

python - 使用Application Factory实现Flask-WhooshAlchemy

转载 作者:行者123 更新时间:2023-12-03 17:04:27 24 4
gpt4 key购买 nike

如果应用是在全球范围内创建的

__init__.py

from flask import Flask

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


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

运行

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

__init__.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中向Application Factory注册 whooshalchemy.whoosh_index(app, Post),以便像上一个示例一样,可以在views.py中使用 whoosh_search

最佳答案

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

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

关于python - 使用Application Factory实现Flask-WhooshAlchemy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23450892/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com