溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

flask里實(shí)現(xiàn)分頁功能的方法

發(fā)布時間:2020-07-31 14:55:20 來源:億速云 閱讀:209 作者:清晨 欄目:編程語言

小編給大家分享一下flask里實(shí)現(xiàn)分頁功能的方法,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!

在web開發(fā)中,分頁是必不可少的功能,F(xiàn)lask實(shí)現(xiàn)展示內(nèi)容的分頁也非常簡單,這里通過實(shí)例來學(xué)習(xí)一下Flask如何為網(wǎng)站分頁。

首先,自定義一個分頁工具類page_utils:

from urllib import urlencode
class Pagination(object):
    def __init__(self, current_page, total_count, base_url, params, per_page_count=10, max_pager_count=11):
        try:
            current_page = int(current_page)
        except Exception as e:
            current_page = 1
        if current_page <=0:
            current_page = 1
        self.current_page = current_page
        self.total_count = total_count
        self.per_page_count = per_page_count
        max_page_num, div = divmod(total_count, per_page_count)
        if div:
            max_page_num += 1
        self.max_page_num = max_page_num
        self.max_pager_count = max_pager_count
        self.half_max_pager_count = int((max_pager_count - 1) / 2)
        self.base_url = base_url
        import copy
        params = copy.deepcopy(params)
        get_dict = params.to_dict() 
        self.params = get_dict
    @property
    def start(self):
        return (self.current_page - 1) * self.per_page_count
    @property
    def end(self):
        return self.current_page * self.per_page_count 
    def page_html(self):
        if self.max_page_num <= self.max_pager_count:
            pager_start = 1
            pager_end = self.max_page_num
        # 如果總頁數(shù) > 11
        else:
            if self.current_page <= self.half_max_pager_count:
                pager_start = 1
                pager_end = self.max_pager_count
            else:
                if (self.current_page + self.half_max_pager_count) > self.max_page_num:
                    pager_end = self.max_page_num
                    pager_start = self.max_page_num - self.max_pager_count + 1   #倒這數(shù)11個
                else:
                    pager_start = self.current_page - self.half_max_pager_count
                    pager_end = self.current_page + self.half_max_pager_count
        page_html_list = []
        self.params['page'] = 1
        first_page = '<li><a href="%s?%s">首頁</a></li>'.decode("utf-8") % (self.base_url,urlencode(self.params),)
        page_html_list.append(first_page)
        self.params["page"] = self.current_page - 1
        if self.params["page"] < 1:
            pervious_page = '<li class="disabled"><a href="%s?%s" aria-label="Previous">上一頁</span></a></li>'.
            decode("utf-8") % (self.base_url, urlencode(self.params))
        else:
            pervious_page = '<li><a href = "%s?%s" aria-label = "Previous" >上一頁</span></a></li>'.decode("utf-8") % 
            ( self.base_url, urlencode(self.params))
        page_html_list.append(pervious_page)
        # 中間頁碼
        for i in range(pager_start, pager_end + 1):
            self.params['page'] = i
            if i == self.current_page:
                temp = '<li class="active"><a href="%s?%s">%s</a></li>' % (self.base_url,urlencode(self.params), i,)
            else:
                temp = '<li><a href="%s?%s">%s</a></li>' % (self.base_url,urlencode(self.params), i,)
            page_html_list.append(temp)
        self.params["page"] = self.current_page + 1
        if self.params["page"] > self.max_page_num:
            self.params["page"] = self.current_page
            next_page = '<li class="disabled"><a href = "%s?%s" aria-label = "Next">下一頁</span></a></li >'.decode
            ("utf-8") % (self.base_url, urlencode(self.params))
        else:
            next_page = '<li><a href = "%s?%s" aria-label = "Next">下一頁</span></a></li>'.decode("utf-8") % 
            (self.base_url, urlencode(self.params))
        page_html_list.append(next_page)
        self.params['page'] = self.max_page_num
        last_page = '<li><a href="%s?%s">尾頁</a></li>'.decode("utf-8") % (self.base_url, urlencode(self.params),)
        page_html_list.append(last_page)
        return ''.join(page_html_list)

自定義方法中的參數(shù):

current_page——表示當(dāng)前頁。

total_count——表示數(shù)據(jù)總條數(shù)。

base_url——表示分頁URL前綴,請求的前綴獲取可以通過Flask的request.path方法,無需自己指定。

例如:我們的路由方法為@app.route('/test'),request.path方法即可獲取/test。

params——表示請求傳入的數(shù)據(jù),params可以通過request.args動態(tài)獲取。

例如:我們鏈接點(diǎn)擊為:http://localhost:5000/test?page=10,此時request.args獲取數(shù)據(jù)為ImmutableMultiDict([('page', u'10')])

per_page_count——指定每頁顯示數(shù)。

max_pager_count——指定頁面最大顯示頁碼

接著,我們使用一個測試方法來使用這個工具類,達(dá)到分頁效果,test.py:

from flask import Flask, render_template, request
from page_utils import Pagination
app = Flask(__name__) 
@app.route('/test')
def test():
    li = []
    for i in range(1, 100):
        li.append(i)
    pager_obj = Pagination(request.args.get("page", 1), len(li), request.path, request.args, per_page_count=10)
    print(request.path)
    print(request.args)
    index_list = li[pager_obj.start:pager_obj.end]
    html = pager_obj.page_html()
    return render_template("obj/test.html", index_list=index_list, html=html)
if __name__ == '__main__':
    app.run(debug=True)

在上面的程序中,li為我們要分頁的對象,數(shù)組list,我們獲取到這個list之后,把他用工具類中的起止方法包起來。

傳遞數(shù)據(jù)用包裝后的list,這樣就達(dá)到了需要哪一段數(shù)據(jù)我們傳遞哪一段的效果,包裝的方法:index_list = li[pager_obj.start:pager_obj.end]

我們用一個HTML頁面去顯示它,分頁樣式不是重點(diǎn),我們這里直接引入bootstrap封裝好的分頁效果,代碼如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap.min.css') }}">
    <style>
        .container{
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div>
        <div class="row " style="margin-top: 10px">
                <ul>
                    {% for foo in index_list %}
                        <li>{{ foo }}:這是列表內(nèi)容~~</li>
                    {% endfor %}
                </ul>
                <nav aria-label="Page navigation">
                    <ul>
                        {{ html|safe }}
                    </ul>
                </nav>
        </div>
    </div>
</body>
</html>

這樣一個分頁的效果就做好了,我們查看效果,如下圖:

flask里實(shí)現(xiàn)分頁功能的方法

看完了這篇文章,相信你對flask里實(shí)現(xiàn)分頁功能的方法有了一定的了解,想了解更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI