#最近做了一个前后端分离的分页操作
#有两种操作方式
#第一种为基于插件的分页
paginate(page, per_page, error_out=True)
page 当前页数
per_page 每页显示的条数
error_out 是否打印错误信息
paginate的属性
paginate.page 当前页数
paginate.pages 总页数
paginate.total 数据总条数
paginate.has_prev 是否存在上一页
返回布尔值
paginate.has_next 是否存在下一页
返回布尔值
paginate.iter_pages() 所有页码
返回列表 如[1, 2, 3, 4]
paginate(page, per_page,error_out).items
返回当前页的所有数据
@stu.route('/stupage/')
def stu_page():
page = int(request.args.get('page', 1))
per_page = int(request.args.get('per_page', 2))
paginate = Student.query.order_by('-s_id').paginate(page, per_page, error_out=False)
stus = paginate.items
return render_template('stupage.html', paginate=paginate, stus=stus)
#第二种为手写的分页操作
@menus.route('/get2', methods=['GET'])
#@login_required
def get2():
if request.method == 'GET':
try:
params = request.args or request.get_json() or request.form
page = params.get('page', type=int, default=1) # 获取页码,默认第一页
per_page = params.get('per_page', type=int, default=2) # 每页显示条数
name = Menus.query.order_by("id").all()
count = len(name)
start = (page - 1) * per_page
end = start + per_page
l = []
for i in range(count):
data = {}
menu_id = name[i].id
data["id"] = name[i].id
data["name"] = name[i].menu_name
data["menu_status"] = name[i].menu_status
data["type"] = name[i].menu_type
data["code"] = name[i].menu_code
data["icon"] = name[i].menu_icon
data["url"] = name[i].menu_url
l.append(data)
name2 = Submenus.query.filter_by(menu_id=menu_id).order_by("id").all()
count2 = len(name2)
l3 = []
for ii in range(count2):
data2 = {}
data2["id"] = name2[ii].id
data2["name"] = name2[ii].submenu_name
data2["type"] = name2[ii].submenu_type
data2["menu_id"] = name2[ii].menu_id
data2["submenu_status"] = name2[ii].submenu_status
data2["url"] = name2[ii].submenu_url
data2["icon"] = name2[ii].submenu_icon
data2["code"] = name2[ii].submenu_code
data2["children"] = l3
l.append(data2)
total_count = len(l)
a = total_count / per_page
total_pages = math.ceil(a)
current_page=page
l1 = l[start:end] # 对数据经行取值
data = {"message": "查询一级菜单成功", "resultCode": "0", "resultData": l1,"total_count":total_count,"total_pages":total_pages,"current_page":current_page}
return json.dumps(data, ensure_ascii=False)
except Exception as e:
print("e",e)
db.session.rollback()
data = {"message": "查询一级菜单失败", "resultCode": "000000104"}
return json.dumps(data)
finally:
db.session.close()