今天给大家分享下flask分页查询的方法,直接上代码:
前端使用jinja2模板
{% if pages.is_prev == 1 %}
<li>
<a href="{{ pages.url }}&p=1" ><span>首页</span></a>
</li>
{% endif %}
{% for idx in pages.range %}
{% if idx == pages.current %}
<li class="active"><a href="javascript:void(0);">{{ idx }}</a></li>
{% else %}
<li><a href="{{ pages.url }}&p={{idx}}">{{ idx }}</a></li>
{% endif %}
{% endfor %}
{% if pages.is_next == 1 %}
<li>
<a href="{{ pages.url }}&p={{ pages.total_pages }}" ><span>尾页</span></a>
</li>
{% endif %}
在后端写入自定义的分页类:
def iPagination( params ):
import math
ret = {
"is_prev":1,
"is_next":1,
"from" :0 ,
"end":0,
"current":0,
"total_pages":0,
"page_size" : 0,
"total" : 0,
"url":params['url']
}
total = int( params['total'] )
page_size = int( params['page_size'] )
page = int( params['page'] )
display = int( params['display'] )
total_pages = int( math.ceil( total / page_size ) )
total_pages = total_pages if total_pages > 0 else 1
if page <= 1:
ret['is_prev'] = 0
if page >= total_pages:
ret['is_next'] = 0
semi = int( math.ceil( display / 2 ) )
if page - semi > 0 :
ret['from'] = page - semi
else:
ret['from'] = 1
if page + semi <= total_pages :
ret['end'] = page + semi
else:
ret['end'] = total_pages
ret['current'] = page
ret['total_pages'] = total_pages
ret['page_size'] = page_size
ret['total'] = total
ret['range'] = range( ret['from'],ret['end'] + 1 )
return ret
在我们需要的视图函数使用自定义的分页类:
@account_blue.route("/index")
def index():
"""
:return:
"""
resp_data={}
query=User.query
# 总页数
total=query.count()
# 获得当前页数
page=request.args.get("p",1)
try:
page=int(page)
if page>total:
abort(404)
except Exception as e:
abort(404)
#自定义分页类需要的参数
page_params={
"total":total,
#每页显示多少条数据
"page_size":constant.PAGE_SIZE,
#当前页
"page":page,
# 显示多少页
"display":constant.DISPLAY,
#使用键值对的方式设置在请求路径中
"url":request.full_path.replace("&p={}".format(page),"")
}
# 分页类
pages=iPagination(page_params)
#开始数据
offset=(page-1)*constant.PAGE_SIZE
#结束
limit=page*constant.PAGE_SIZE
# 根据uid降序查询
list = query.order_by(User.uid.desc()).all()[offset:limit]
resp_data["list"] = list
resp_data["pages"]=pages
return ops_rander("account/index.html",context=resp_data)
以上便是flask分页查询,详细说明的全部内容,更多内容干货可关注慕课网~