本文主要是介绍使用 flask_whooshalchemyplus jieba 为 Flask 添加 搜索 功能,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
正在利用Flask仿造知乎,核心的功能都实现了,就差个搜索,可惜flask_SqlAlchemy尚未支持全文搜索,遂取网友经验,用flask_whooshalchemyplus来实现,此文记录下使用方法,以供后续自己和其他同学查找学习之用
备注:flask_whooshalchemy尚未支持py3,flask_whooshalchemy和plus原生都支持英文不支持中文,我们采用公认比较优秀的jieba来做中文分词
1.安装flask_whooshalchemyplus
pip install flask_whooshalchemyplus
2.config.py中的配置
#coding:utf-8
import os
basedir = os.path.abspath(os.path.dirname(__file__))#基类 Config 中包含通用配置
class Config:#省略#设置索引文件存放文件夹位置WHOOSH_BASE = os.path.join(basedir, 'WHOOSH_BASE_INDEX')
3.app/init.py工厂函数中的初始化
import flask_whooshalchemyplus#create_app() 函数就是程序的工厂函数,接受一个参数,是程序使用的配置名
def create_app(config_name):app = Flask(__name__)#配置类在 config.py 文件中定义,其中保存的配置可以使用 Flask app.config 配置对象提供的 from_object() 方法直接导入程序app.config.from_object(config[config_name])config[config_name].init_app(app)#蓝本在工厂函数 create_app() 中注册到程序上from .auth import auth as auth_blueprintapp.register_blueprint(auth_blueprint, url_prefix='/auth')from .main import main as main_blueprintapp.register_blueprint(main_blueprint)from .api_1_0 import api as api_1_0_blueprintapp.register_blueprint(api_1_0_blueprint, url_prefix='/api/v1.0')#程序创建并配置好后,就能初始化扩展了。在之前创建的扩展对象上调用 init_app() 可以完成初始化过程。db.init_app(app)login_manager.init_app(app)mail.init_app(app)monment.init_app(app)pagedown.init_app(app)flask_whooshalchemyplus.init_app(app)#工厂函数返回创建的程序示例return app
4.models.py模型Post类中添加searchable
#文章内容模型
class Post(db.Model):__tablename__ = 'posts'__searchable__ = ['body']
5.view.py视图函数中添加索引
def askquestion():form = AskQuestionForm()if current_user.can(Permission.WRITE_ARTICLES) and \form.validate_on_submit():post = Post(title=form.title.data,body=form.body.data,author=current_user._get_current_object())db.session.add(post)return redirect(url_for('.index'))page = request.args.get('page', 1, type=int)show_followed = Falseif current_user.is_authenticated:show_followed = bool(request.cookies.get('show_followed', ''))if show_followed:query = current_user.followed_postselse:query = Post.querypagination = query.order_by(Post.timestamp.desc()).paginate(page, per_page=current_app.config['FLASKY_POSTS_PER_PAGE'],error_out=False)posts = pagination.items#有了新问题就提交一次索引import flask_whooshalchemyplusflask_whooshalchemyplus.index_one_model(Post)return render_template('askquestion.html', form=form, posts=posts,show_followed=show_followed, pagination=pagination)
5.view.py视图函数中添加Post.query.whoosh_search(keyword)来查找前端表单传过来的要查找的关键词
#搜索文章的路由
@main.route('/search/', methods=['GET', 'POST'])
@login_required
def search():#获取搜索表单传过来的数据keyword = request.form.get('q','default value')page = request.args.get('page', 1, type=int)show_followed = Falsepagination = Post.query.whoosh_search(keyword).order_by(Post.timestamp.desc()).paginate(page, per_page=current_app.config['FLASKY_POSTS_PER_PAGE'],error_out=False)posts = pagination.itemsreturn render_template('searched.html',posts=posts, show_followed=show_followed, pagination=pagination)
6.前端base.html查找表单,搜索zhihu,得到结果
<div role="search" id="zh-top-search" class="zu-top-search">
<form method="POST" action="{{ url_for('main.search') }}" id="zh-top-search-form" class="zu-top-search-form"><input type="hidden" name="type" value="content">
<label for="q" class="hide-text">知乎搜索</label><input type="text" class="zu-top-search-input" id="q" name="q" autocomplete="off" value="" maxlength="100" placeholder="搜索你感兴趣的内容...">
<button type="submit" class="zu-top-search-button"><span class="hide-text">搜索</span><span class="sprite-global-icon-magnifier-dark"></span></button>
</form>
</div>
7.以上都是基础的应用,如果想加入中文搜索支持,可以用jieba分词库来搞,需要下面这样加点改动就可以了
安装jieba
pip install jieba
修改models.py中的Post模型类,添加analyzer = ChineseAnalyzer()
from jieba.analyse.analyzer import ChineseAnalyzer#文章内容模型
class Post(db.Model):__tablename__ = 'posts'__searchable__ = ['title']__analyzer__ = ChineseAnalyzer()
搜索”测试”,可以得到标题包含测试关键词的问题
如需更多参考,可以看我的项目,地址:
https://github.com/584807419/ZhiHu
Flask-WhooshAlchemyPlus项目地址:
https://github.com/Revolution1/Flask-WhooshAlchemyPlus
这篇关于使用 flask_whooshalchemyplus jieba 为 Flask 添加 搜索 功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!