1、安装 flask_whooshalchemyplus
方式一: pip install flask_whooshalchemyplus
方式二: git clone https://github.com/Revolution1/Flask-WhooshAlchemyPlus.git
cd Flask-WhooshAlchemyPlus
python setup.py install
版本0.7.6
pip install SQLAlchemy==1.3.24
需要注意SQLAlchemy版本,1.4会出现问题
2、创建工厂类配置
__init__.py
app = Flask(__name__, template_folder='../templates')
app.config.from_object(config)
app.before_request(jwt_authentication)
db.init_app(app)
# flask_whooshalchemyplus.init_app(app)
with app.app_context():
flask_whooshalchemyplus.index_all(app)
cache.init_app(app)
app.register_blueprint(user_bp)
app.register_blueprint(course_bp)
# 第三方登录
app.register_blueprint(oauth2_bp)
# vip 表
app.register_blueprint(vip_bp)
# 购买相关
app.register_blueprint(pay_bp)
# setup_log('testing')
cors = CORS(app, resources={r"/*/*": {"origins": "*"}})
3、配置文件
conf.py
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class DefaultConfig(object):
"""
Flask默认配置
"""
# flask-sqlalchemy使用的参数
SQLALCHEMY_DATABASE_URI = ''
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_ECHO = False
JWT_SECRET = 'LSJFLSJFLWE23O9UDFNSDF'
CACHE_TYPE = 'redis' # 使用redis作为缓存 simple/memcached/uwsgi/redis/filesystem
# CACHE_KEY_PREFIX # 设置cache_key的前缀
CACHE_REDIS_HOST = '' # redis地址
CACHE_REDIS_PORT = '6379' # redis端口
# CACHE_REDIS_PASSWORD # redis密码
CACHE_REDIS_DB = 2 # 使用哪个数据库
# CACHE_DIR = 'D:\code\information_items'
# 索引存放位置
WHOOSH_BASE = os.path.join(basedir, 'WHOOSH_BASE_INDEX')
4、model设置
class Tag(Base):
"""
课程标签
"""
__tablename__ = 'tag'
__searchable__ = ['title', 'desc']
__analyzer__ = ChineseAnalyzer()
id = db.Column(db.Integer, primary_key=True, doc='课程标签id')
title = db.Column(db.String(16), doc='课程类别')
desc = db.Column(db.String(256), doc='课程描述')
sequence = db.Column(db.Integer, doc='展示顺序', default=10)
course = db.relationship('Course', secondary='course_tag', backref=db.backref('tags'))
def __str__(self):
return self.title
5、搜索数据
parse = reqparse.RequestParser()
parse.add_argument('q')
args = parse.parse_args()
search = args['q']
tag_list = Tag.query.whoosh_search(search).all()
6、更新数据
更新有索引的数据后,需要将对应的索引添加
db.session.add(course)
db.session.commit()
flask_whooshalchemyplus.index_one_model(Course)