- 搞了半天没搞好, 不过最后还是搞好了,嘿嘿嘿, 美滋滋,来首 Good Time
- 好了好了, 进入正题
- 删库跑路, 哈哈哈 假的, 我是直接把database删了, 然后再创
- 直接跑的话会报错, 比如像db, 还有manage.py啥的懒得写了
- models.py
import flask_whooshalchemyplus
from jieba.analyse import ChineseAnalyzer
class Student(db.Model):
__tablename__ = 'student'
__searchable__ = ['name', 'uuid']
__analyzer__ = ChineseAnalyzer()
id = db.Column(db.Integer, primary_key=True)
uuid = db.Column(db.String(255), unique=True)
name = db.Column(db.String(100))
flask_whooshalchemyplus.init_app(app)
if __name__ == '__main__':
db.create_all()
- 运行models.py
- forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
class SearchForm(FlaskForm):
key = StringField(
label='关键词',
description='关键词',
validators=[
DataRequired('请输入关键词!')
],
render_kw={
'placeholder': '请输入关键词'
}
)
submit = SubmitField(
label='查询'
)
- views.py
@home.route('/search/', methods=['POST', 'GET'])
def search():
form = SearchForm()
if form.validate_on_submit():
data = form.data
flask_whooshalchemyplus.whoosh_index(app, Student)
return redirect(url_for('home.search_results', key=data['key']))
return render_template('home/search.html', form=form)
@home.route('/search_results/<string:key>')
def search_results(key):
results = Student.query.whoosh_search(key).all()
return render_template('home/search_results.html', key=key, results=results, count=count)
- search.html
<form method="post">
{{ form.key }}
{{ form.csrf_token }}
{{ form.submit }}
</form>
- search_results.html
"{{ key }}"共有{{ count }}条
<br>
{% for i in results %}
{{ i.name }}
{{ i.uuid }}
<br>
{% endfor %}
- 貌似有时行有时不行 还是用数据库自带的模糊搜索吧, 也挺好用的