思路
1.在前端页面向服务器提交数据,这里使用post方法
2.服务器端view层接受到数据,在通过model层从数据库中查找数据并返回
3.将查询到的数据通过view层渲染到templates中进行显示
实现
第一步:在前端页面上定制搜索框
定制过程中使用了bootstrap框架
{# 搜索框设置 #}
<div class="search-design" >
<form method="post" class="form-inline" action="{{ url_for('index.content_search') }}" >
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<input class="form-control" type="text" name="search"
placeholder="请输入搜索内容" >
<button type="submit" class="btn btn-primary">搜索</button>
</form>
</div>
如果想要演示的话,记得将bootstrap的css、js进行引入
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdn.staticfile.org/popper.js/1.15.0/umd/popper.min.js"></script> <script src="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js">></script>
效果:
因为项目中的app开启了csrf校验,因此在前端进行post提交时要加上这行代码,加载csrf令牌
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
第二步 编写视图函数
index_bp是个人创建的blueprint对象,用于放置view函数,对其进行统一管理
#搜索功能
@index_bp.route('/search',methods=['post','get'])
@user_login_data
def content_search():
print('----asd-------')
keyword=request.form.get('search')
print(keyword)
print('1235---------')
if keyword is None:
keyword = " "
try:
#通过model层的News对象,在数据库中检索信息
news_search = News.query.filter(News.title.like("%" + keyword + "%")).all()
print('------------------------------------')
print(news_search)
print('-----------------------------------')
except Exception as e:
current_app.logger.error(e)
return jsonify(errno=RET.DBERR, errmsg="搜索内容失败")
# 4.将新闻对象列表转成,字典列表
search_news_list = []
for item in news_search:
search_news_list.append(item.to_dict())
# 5.查询所有的分类数据
try:
categories = Category.query.all()
except Exception as e:
current_app.logger.error(e)
return jsonify(errno=RET.DBERR, errmsg="获取分类失败")
# 6.将分类的对象列表转成,字典列表
search_category_list = []
for category in categories:
search_category_list.append(category.to_dict())
# 7.拼接用户数据,渲染页面
data = {
# 如果user有值返回左边的内容, 否则返回右边的值
"user_info": g.user.to_dict() if g.user else "",
"news_list": search_news_list,
"category_list": search_category_list,
}
# 渲染页面
return render_template("news/search.html", data=data)
最终效果
参考资料
Flask 项目中form表单出现CSRF missing and The CSRF token is invalid.