Flask-flask中的后台分页查询实现

本文介绍了在Flask应用中处理大量数据时如何使用Flask-SQLAlchemy的paginate方法进行后台分页查询,以及两种实现方式,包括使用paginate()函数和手动限制查询。这两种方法有助于提高页面加载速度和用户体验。
摘要由CSDN通过智能技术生成

在后台查询数据并在前台展示的场景中,当数据量较大时,页面加载会非常缓慢,此时建议使用后台分页查询的形式。在flask中,基于Flask-SQLAlchemy可以使用以下方式实现。

方法一:

Flask-SQLAlchemy 提供了一个 paginate()查询方法,参考:Flask 学习-73.Flask-SQLAlchemy 分页查询paginate_flasksqlalchemy分页查询_上海-悠悠的博客-CSDN博客

page4 = Server.query.paginate(page=4, per_page=2)
print(page4.items)
page3 = page4.prev()
print(page3.items)

查看源码:

    def paginate(
        self,
        select: sa.sql.Select[t.Any],
        *,
        page: int | None = None,
        per_page: int | None = None,
        max_per_page: int | None = None,
        error_out: bool = True,
        count: bool = True,
    ) -> Pagination:
        """Apply an offset and limit to a select statment based on the current page and
        number of items per page, returning a :class:`.Pagination` object.

        The statement should select a model class, like ``select(User)``. This applies
        ``unique()`` and ``scalars()`` modifiers to the result, so compound selects will
        not return the expected results.

        :param select: The ``select`` statement to paginate.
        :param page: The current page, used to calculate the offset. Defaults to the
            ``page`` query arg during a request, or 1 otherwise.
        :param per_page: The maximum number of items on a page, used to calculate the
            offset and limit. Defaults to the ``per_page`` query arg during a request,
            or 20 otherwise.
        :param max_per_page: The maximum allowed value for ``per_page``, to limit a
            user-provided value. Use ``None`` for no limit. Defaults to 100.
        :param error_out: Abort with a ``404 Not Found`` error if no items are returned
            and ``page`` is not 1, or if ``page`` or ``per_page`` is less than 1, or if
            either are not ints.
        :param count: Calculate the total number of values by issuing an extra count
            query. For very complex queries this may be inaccurate or slow, so it can be
            disabled and set manually if necessary.

        .. versionchanged:: 3.0
            The ``count`` query is more efficient.

        .. versionadded:: 3.0
        """

参数说明:
page: int,指定页码,从1开始
per_page: int,每一页显示几条数据
max_per_page:每页显示最大值当指定了max_per_page时,per_page会受到这个值的限制
error_out:是否抛出错误(默认为True)
count:是否计数,默认为True

返回值:
调用 paginate()查询方法会返回一个Pagination 对象的实例

Pagination类对象的属性主要有:
has_next:如果在目前页后至少还有一页的话,返回 True。
has_prev:如果在目前页之前至少还有一页的话,返回 True。
next_num:下一页的页面数。
prev_num:前一页的页面数。

另外还有如下的可调用方法:
iter_pages():一个迭代器,返回一个在分页导航中显示的页数列表。
prev():上一页的分页对象。
next():下一页的分页对象。

方法二:

利用限制查询方式手动实现分页,参考:Flask 查询,分页,排序及逻辑运算与聚合:_flask分页查询_Gray area的博客-CSDN博客

filters=[] # 组装通用查询过滤器filter,略
offset = (int(paging_start)-1)*int(paging_size)   
data_qry = User.query.filter(and_(*filters)).offset(offset).limit(paging_size).all()
或者
data_qry = User.query.offset(offset).limit(paging_size).all()
Flask-Paginate是一个Flask扩展,它提供了一种简单的方法来实现分页功能。它基于SQLAlchemy,并且可以与任何SQLAlchemy支持的数据库一起使用。 首先,你需要安装Flask-Paginate扩展。可以通过以下命令来安装: ``` pip install Flask-Paginate ``` 然后,你需要导入Flask-Paginate扩展并创建一个分页器。以下是一个简单的示例: ```python from flask_paginate import Pagination, get_page_args @app.route('/') def index(): # 获取当前页码和每页显示的数量 page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page') # 从数据库获取数据 data = get_data_from_database(offset=offset, per_page=per_page) # 创建分页器 pagination = Pagination(page=page, per_page=per_page, total=count_total_items_in_database(), css_framework='bootstrap4') # 渲染模板 return render_template('index.html', data=data, pagination=pagination) ``` 在上面的示例,我们首先使用`get_page_args`函数从请求参数获取当前页码和每页显示的数量。然后,我们从数据库获取数据,并使用`Pagination`类创建一个分页器对象。最后,我们将数据和分页器对象传递给模板进行渲染。 在模板,你可以使用`prev_href`,`next_href`和`links`属性来生成分页器的HTML代码。以下是一个简单的示例: ```html <div class="pagination"> <a href="{{ pagination.prev_href() }}">Previous</a> {% for page in pagination.links %} {% if page == '...' %} <span class="ellipsis">...</span> {% elif page == pagination.page %} <span class="current">{{ page }}</span> {% else %} <a href="{{ page }}">{{ page }}</a> {% endif %} {% endfor %} <a href="{{ pagination.next_href() }}">Next</a> </div> ``` 上面的代码会生成一个类似于以下HTML代码的分页器: ```html <div class="pagination"> <a href="/?page=1&per_page=10">Previous</a> <a href="/?page=1&per_page=10">1</a> <a href="/?page=2&per_page=10">2</a> <a href="/?page=3&per_page=10">3</a> <a href="/?page=4&per_page=10">4</a> <a href="/?page=5&per_page=10">5</a> <span class="ellipsis">...</span> <a href="/?page=10&per_page=10">10</a> <a href="/?page=2&per_page=10">Next</a> </div> ``` 此外,你还可以使用`prev_disabled`和`next_disabled`属性来禁用“上一页”和“下一页”链接,如果当前页码是第一页或最后一页的话。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值