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()
##  https://www.cnblogs.com/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>

 效果如下:

posted @ 2022-07-20 09:37  liucx  阅读(845)  评论(0编辑  收藏  举报