flask_paginate對mysql數據進行分頁查詢
使用flask_paginate對mysql數據進行分頁查詢,這里介紹使用原生sql方法,也可以使用SQLAlchemy對數據做查詢
app.py
from flask import Flask,render_template,redirect
from flask import request
from db_helper import MySQL
from flask_paginate import Pagination,get_page_parameter
app = Flask(__name__)
@app.route('/test/', defaults={'page': 1})
@app.route('/test/<page>')
def test(page):
page = request.args.get(get_page_parameter(), type=int, default=int(page))
dbconn = MySQL(host='10.10.10.1', user='root', passwd='passwd', db='test', port=3306, charset="utf8mb4")
select_sql = "select * from server"
# 分頁數
page_num = 5
filter_sql = (" ORDER BY id ASC LIMIT {limit} offset {offset}".format(limit=page_num, offset = (page_num * int(page)-page_num)))
ret_sql = select_sql + filter_sql
table_data = dbconn.fetch_rows(ret_sql, as_dict=True)
table_data_total = len(dbconn.fetch_rows(select_sql, as_dict=True))
paginate = Pagination(page=page, total=table_data_total,per_page=page_num)
return render_template('test.html', table_ret = table_data, paginate=paginate)
if __name__ == "__main__":
app.run()
## http://www.rzrgm.cn/liucx/
test.html
<div class="col">
<table class="table table-bordered table-hover">
<thead>
<th>服務器名</th>
<th>服務器IP</th>
<th>服務器端口</th>
<th>服務器用戶</th>
<th>操作</th>
</thead>
<tbody id="tbodycontent">
{% if table_ret %}
{% for row in table_ret %}
<tr>
<td> {{ row.name }}</td>
<td> {{ row.ip }}</td>
<td> {{ row.port }}</td>
<td> {{ row.user }}</td>
<td> </td>
</tr>
{% endfor %}
{% endif %}
</tbody>
</table>
<div class="page_footer"><span class="page_total">共 {{ paginate.total }} 條</span> {{ paginate.links }}</div>
</div>
效果如下:

作者:Liucx
E-mail:57349220@qq.com
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利.

浙公網安備 33010602011771號