Flask - 实现数据分页

目录

一、Flask-SQLAlchemy - 直接获取分页后的数据

1-0 基于 flsk-sqlalchemy 的批量数据插入 - add_all(list)

1-1 Pagination对象的常用属性

1-2 Pagination对象的常用方法

 二、flask-paginate - 对原始数据进行分页


一、Flask-SQLAlchemy - 直接获取分页后的数据

flask-sqlalchemy 官方文档

Flask-SQLAlchemy 实现分页的简单学习

paginate(page=None, per_page=None, error_out=True, max_per_page=None)

Returns per_page items from page page.

If page or per_page are None, they will be retrieved from the request query. If max_per_page is specified, per_page will be limited to that value. If there is no request or they aren’t in the query, they default to 1 and 20 respectively.

如果page或per_page为None,则将从请求查询中检索它们。如果指定了max_per_page,则per_page将限制为该值。如果没有请求或它们不在查询中,则它们分别默认为1和20。

  • When error_out is True (default), the following rules will cause a 404 response(当error_out为True(默认值)时,以下规则将导致404响应):
  • No items are found and page is not 1. - 找不到任何项目且页面不是1.
  • page is less than 1, or per_page is negative. - page小于1,或per_page为负数。
  • page or per_page are not ints. - page或per_page不是整数。
  • When error_out is False, page and per_page default to 1 and 20 respectively.(当error_out为False时,page和per_page分别默认为1和20。)

Returns a Pagination object. - 返回 Pagination 对象

@app.route('/')
@login_required
def index():
    page=request.args.get('page',1,type=int)
        pagination=User.query.order_by(User.createTime.desc()).paginate(page,per_page=12,error_out=False)
    users=pagination.items
    return render_template('index.html', name=current_user.username,users=users,pagination=pagination)

1-0 基于 flsk-sqlalchemy 的批量数据插入 - add_all(list)

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:[email protected]:3306/test'
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
db = SQLAlchemy(app)


class Test(db.Model):
    __tablename__ = 'test'
    id = db.Column(db.INTEGER, primary_key=True)
    name = db.Column(db.String(255), nullable=False)

    def __repr__(self):
        return '<Test %r>' % self.name


def quick_update():
    li = []
    for i in range(100):
        li.append(Test(name='test_%s' % i))
    db.session.add_all(li)
    db.session.commit()


if __name__ == '__main__':
    quick_update()
执行函数出现警告,未影响数据插入(未解决)

 

1-1 Pagination对象的常用属性

  • items 当前页面中的所有记录(比如当前页上有5条记录,items就是以列表形式组织这5个记录)
  • query 当前页的query对象(通过query对象调用paginate方法获得的Pagination对象)
  • page 当前页码(比如当前页是第5页,返回5)
  • per_page 每页显示的记录条数量,若不指定,默认显示20个记录
  • prev_num 上一页页码
  • next_num 下一页页码
  • has_next 是否有下一页 True/False
  • has_prev 是否有上一页 True/False
  • pages 查询得到的总页数
  • total 总的记录条数
  • error_ out
    • 当其设为 True 时(默认值),如果请求的页数超出了范围,则会返回 404 错误;
    • 如果 设为 False,页数超出范围时会返回一个空列表。
def select():
    pagination = Test.query.paginate(page=1, per_page=10, error_out=True)
    print('items 当前页面的所有记录:',pagination.items)
    print('page 当前页码:',pagination.page)
    print('per_page 每页显示记录条数:',pagination.per_page)
    print('has_prev 是否有上一页:',pagination.has_prev)
    print('prev_num 上一页页码:',pagination.prev_num)
    print('has_next 是否有下一页:',pagination.has_next)
    print('next_num 下一页页码:',pagination.next_num)
    print('pages 查询得到的总页数:',pagination.pages)
    print('total 总记录条数:',pagination.total)


if __name__ == '__main__':
    select()

 

1-2 Pagination对象的常用方法

  • prev() 上一页的分页对象Pagination
  • next() 下一页的分页对象Pagination
  • iter_pages(left_edge=2,left_current=2,right_current=5,right_edge=2)
    • iter_pages 用来获得针对当前页的应显示的分页页码列表。
    • 假设当前共有100页,当前页为50页,按照默认的参数设置调用iter_pages获得的列表为:[1,2,None,48,49,50,51,52,53,54,55,None,99,100]

 二、flask-paginate - 对原始数据进行分页

flask-paginate 官方文档