05-Flask之?dāng)?shù)據(jù)查詢(分頁)

一、批量數(shù)據(jù)產(chǎn)生(數(shù)據(jù)庫存儲過程)

# 商品列表表
# 商品模型類
class Goods(db.Model):
    # 商品id,主鍵
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    # 商品名稱
    name = db.Column(db.String(20))
    # 商品圖片
    icon = db.Column(db.String(255))
    # 商品價格
    price = db.Column(db.Integer)
    # 商品描述
    detail = db.Column(db.String(255))


# 表單結(jié)構(gòu)goods
mysql> desc goods;
+--------+--------------+------+-----+---------+----------------+
| Field  | Type         | Null | Key | Default | Extra          |
+--------+--------------+------+-----+---------+----------------+
| id     | int(11)      | NO   | PRI | NULL    | auto_increment |
| name   | varchar(20)  | NO   |     | NULL    |                |
| icon   | varchar(255) | NO   |     | NULL    |                |
| price  | int(11)      | NO   |     | NULL    |                |
| detail | varchar(255) | NO   |     | NULL    |                |
+--------+--------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)



# 存儲過程: 創(chuàng)建商品數(shù)據(jù)
# insert into goods(name,icon,price,detail) value(name,icon,price,detail)
delimiter //
create procedure add_goods(num int(4))
begin
    # 定義變量
    declare _i,_price,_temp int(4) default 0;
    declare _name,_icon,_detail varchar(255) default '';
    declare BASE_PATH varchar(255) default '/static/img/';

    # 循環(huán)
    while _i<num do
        # 設(shè)置變量
        set _temp = round(rand()*10000+1000);
        set _name = concat(_temp,'-商品名稱');
        set _temp = round(rand()*5+1);
        case _temp
        when 1 then
            set _icon = concat(BASE_PATH,'1.jpg');
        when 2 then
            set _icon = concat(BASE_PATH,'2.jpg');
        when 3 then
            set _icon = concat(BASE_PATH,'3.jpg');
        when 4 then
            set _icon = concat(BASE_PATH,'4.jpg');
        when 5 then
            set _icon = concat(BASE_PATH,'5.jpg');
        when 6 then
            set _icon = concat(BASE_PATH,'6.jpg');
        else
            set _icon = concat(BASE_PATH,'1.jpg');
        end case;
        set _temp = round(rand()*10000+1000);
        set _price = _temp;
        set _temp = round(rand()*10000+1000);
        set _detail = concat(_temp,'-Apple/蘋果 iPhone 7 Plus蘋果7代7pluss國行美版三網(wǎng)5.5寸7p手機');

        # 插入數(shù)據(jù)
        insert into goods(name,icon,price,detail) value(_name,_icon,_price,_detail);

        # 修改次數(shù)
        set _i = _i + 1;
    end while;

    # 顯示數(shù)據(jù)
    select * from goods;
end
//
delimiter ;


# 調(diào)用存儲過程
call add_goods(30);

備注: 存儲過程的添加是要在表單對應(yīng)的數(shù)據(jù)庫中進(jìn)行操作?。?!

二、SQLAlchemy數(shù)據(jù)查詢之分頁操作(手動)

  • 手動操作(自己查詢關(guān)聯(lián))
@blue.route('/goodslist/<int:num>/<int:per>/')
def goodslist(num,per):
    # 第num頁
    # 每頁顯示per行
    goods = Goods.query.offset((num-1) * per).limit(per)
    
    return render_template('goodslist.html', goods=goods
  • flask自帶(paginate)
- 當(dāng)前頁面(屬性)
    page  
- 當(dāng)前頁面中的記錄(屬性)
    items
- 上一頁頁碼(屬性)
    prev_num
- 下一頁頁碼(屬性)
    next_num
- 如果有上頁返回True(屬性)
    has_prev
- 如果有下頁返回True(屬性)
    has_next
- 查詢得到總頁數(shù)(屬性)
    pages
- 每一頁顯示記錄的數(shù)量(屬性)
    per_page  
- 查詢返回的記錄總數(shù)(屬性)
    total
    
- 返回一個分頁導(dǎo)航中顯示列表
    iter_pages
    
    這個列表最左邊左邊顯示left_edeg頁,
    當(dāng)前頁的左邊顯示left_current頁,
    當(dāng)前頁的右邊顯示right_current頁,
    最右邊顯示right_edeg頁。
    
    例如: 在一個100頁的頁碼中,當(dāng)前頁為第50頁,使用默認(rèn)配置。
    這個方法返回以下頁數(shù): 1、2、None、48、49、50、51、52、53、54、55、None、99、100
    None表示頁數(shù)之間的間隔。
    

@blue.route('/goodslist/<int:num>/<int:per>/')
def goodslist(num,per):
    paginate = Goods.query.paginate(num,per)

    return render_template('goodslist.html', paginate=paginate)

paginate對象中傳遞到模板中進(jìn)行使用,可以使用上述屬性和方法。

三、SQLAlchemy數(shù)據(jù)查詢之分頁操作

接下來以 Jinja2 宏的形式實現(xiàn)的分頁導(dǎo)航,但默認(rèn)這里的處理是通過get請求方式處理的,例如page=1,page=2。

所以想要使用這里,在后續(xù)處理中,需要修改模板,還需要對數(shù)據(jù)請求方式修改為get,而不能通過path方式傳參數(shù),否則使用不了。

  • Jinja2 宏定義的形式實現(xiàn)的分頁導(dǎo)航,分頁模板(_macros.html)
{% macro pagination_widget(pagination, endpoint) %}
    <ul class="pagination">
        <li{% if not pagination.has_prev %} class="disabled"{% endif %}>
            <a href="{% if pagination.has_prev %}{{ url_for(endpoint,page = pagination.page - 1, **kwargs) }}
            {% else %}#{% endif %}">&laquo;
            </a>
        </li>
        {% for p in pagination.iter_pages() %}
            {% if p %}
                {% if p == pagination.page %}
                    <li class="active">
                        <a href="{{ url_for(endpoint, page = p, **kwargs) }}">{{ p }}</a>
                    </li>
                {% else %}
                <li>
                    <a href="{{ url_for(endpoint, page = p, **kwargs) }}">{{ p }}</a>
                </li>
                {% endif %}
            {% else %}
            <li class="disabled">
                <a href="#">&hellip;</a>
            </li>
            {% endif %}
        {% endfor %}
        <li{% if not pagination.has_next %} class="disabled"{% endif %}>
            <a href="{% if pagination.has_next %}{{ url_for(endpoint,page = pagination.page + 1, **kwargs) }}{% else %}#{% endif %}">&raquo;</a>
        </li>
    </ul>
{% endmacro %}

pagination_widget(pagination, endpoint),需要傳入pagination對象,endpoint反向解析位置(即是藍(lán)圖名.函數(shù)名)

_index.html文件中

 {#    商品展示#}
        <ul class="goods">
            {% for goods in pagination.items %}
                <li>
                    <p class="goodsid">商品序號: {{ goods.id }}</p>
                    <p class="name">商品名稱: {{ goods.name }}</p>
                    <p class="price">商品價格: ¥{{ goods.price }}</p>
                    <p class="detail">商品描述: {{ goods.detail }}</p>
                </li>
            {% endfor %}
        </ul>

{#    宏定義形式實現(xiàn)的分頁導(dǎo)航#}
        {% import "_macros.html" as macros %}
        {% if pagination %}
            <div class="pagination">
                {{ macros.pagination_widget(pagination, 'blue.index') }}
            </div>
        {% endif %}

備注: 分頁導(dǎo)航使用的使用bootstrap中的css樣式?。?!

  • views.py文件中
# 首頁
@blue.route('/')
def index():
    # 傳遞的頁碼數(shù)量
    page = int(request.args.get('page') or 1)
    # goodslist = Goods.query.all()

    # 頁碼page,每頁顯示10條
    pageObj = Goods.query.paginate(page,5)

    return render_template('index.html', pagination=pageObj)

pagination包含了所有需要的參數(shù),包括數(shù)據(jù),即一個pagination對象搞定所有。

作者:西門奄
鏈接:http://www.itdecent.cn/u/77035eb804c3
來源:簡書
簡書著作權(quán)歸作者所有,任何形式的轉(zhuǎn)載都請聯(lián)系作者獲得授權(quán)并注明出處。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 一、批量數(shù)據(jù)產(chǎn)生(數(shù)據(jù)庫存儲過程) 備注: 存儲過程的添加是要在表單對應(yīng)的數(shù)據(jù)庫中進(jìn)行操作?。?! 二、SQLAlc...
    EndEvent閱讀 3,517評論 0 3
  • 22年12月更新:個人網(wǎng)站關(guān)停,如果仍舊對舊教程有興趣參考 Github 的markdown內(nèi)容[https://...
    tangyefei閱讀 35,412評論 22 257
  • 第十一章 博客文章 本章將實現(xiàn)Flasky博客的核心功能,允許用戶讀取和撰寫文章。你將學(xué)到一些關(guān)于模板重用、長項目...
    易木成華閱讀 1,132評論 0 1
  • 分頁 REST framework 包含對可定制分頁樣式的支持。這使你可以將較大的結(jié)果集分成單獨的數(shù)據(jù)頁面。分頁 ...
    入間閱讀 1,388評論 0 2
  • 創(chuàng)建新的倉庫并 push 到遠(yuǎn)程倉庫 push 一個已經(jīng)存在的倉庫到遠(yuǎn)程倉庫 操作遠(yuǎn)程倉庫 顯示當(dāng)前綁定的遠(yuǎn)程倉庫...
    風(fēng)亡小窩閱讀 303評論 0 0

友情鏈接更多精彩內(nèi)容