|
google查了不少文章
發現mariadb 翻頁(pagination)功能 沒人寫
只好土法煉鋼自己寫一個
展示:
flask render_template mariadb 翻頁功能 pagination
admin_view.py內寫入
- from app.pagination import pageft
- from math import ceil
- # 秀出所有紀錄
- count_sql = "select * from net_class"
- cursor.execute(count_sql)
- total = len(cursor.fetchall())
- page_num = request.args.get('page', 1, type=int) #抓取初始頁數
- firstcount = 1 # 初始計數
- displaypg = 10 # 每頁顯示幾筆
- lastpg = ceil(total / displaypg)
- if page_num == 1:
- firstcount = 0
- elif page_num == lastpg:
- firstcount = firstcount * page_num + 1
- displaypg = total % displaypg
- else:
- firstcount = firstcount*page_num+1
- # pageft(初始計數, 總筆數, 每頁顯示幾筆, url_for(def路徑))
- page_nav = pageft(firstcount, total, displaypg, "admin_class")
- sql = "SELECT * FROM net_class ORDER BY num ASC limit "+str(firstcount)+","+str(displaypg)
- print("sql:",sql)
- cursor.execute(sql)
- result = cursor.fetchall()
複製代碼
建立 pagination.py
- from flask import request,url_for
- from math import ceil
- def pageft(firstcount,total,displaypg = 20,url=""):
- if request.args.get('page')== None:
- page = 1
- else:
- page = int(request.args.get('page'))
- if page<=0:
- page=1
- lastpg = ceil(total /displaypg) # 最後頁,也是總頁數
- if page == 1:
- prepg = 1
- firstcount = 1
- nextcount = 1 * displaypg
- nextpg = page + 1
- elif page == lastpg:
- firstcount = (page-1) * displaypg+1
- nextcount = total
- nextpg = page
- prepg = page - 1
- else:
- firstcount = (page-1) * displaypg+1
- nextcount = page * displaypg
- prepg = page - 1
- nextpg = page + 1
- pagenav = "顯示 <B>"+ str(firstcount) +"</B>-<B>"+ str(min(nextcount ,total)) +"</B> 筆記錄,共 "+str(total)+" 筆"
- if lastpg <= 1:
- return False
- pagenav += " <a href='"+ url_for(url) +"?page=1'>頁首</a> "
- if prepg:
- pagenav += " <a href='"+url_for(url)+"?page="+str(prepg)+"'>上一頁</a> "
- else:
- pagenav += " <a href='"+url_for(url)+"?page="+str(prepg)+"'>上一頁</a> "
- if nextpg :
- pagenav += " <a href='"+url_for(url)+"?page="+ str(nextpg)+"'>下一頁</a>"
- else:
- pagenav += " <a href='"+url_for(url)+"?page="+ str(nextpg)+"'>下一頁</a>"
- pagenav +=" <a href='"+url_for(url)+"?page="+str(lastpg)+"'>頁尾</a> "
- print("pagenav:",pagenav)
- pagenav += " 到第 <select onchange = "window.location.href=this.value" >\n"
- for i in range(lastpg):
- if i+1 == page:
- pagenav +="<option value='"+url_for(url)+"?page="+str(i+1)+"' selected>"+str(i+1)+"</option>\n"
- else:
- pagenav +="<option value='"+url_for(url)+"?page="+str(i+1)+"'>"+str(i+1)+"</option>\n"
- pagenav += "</select> 頁,共 "+str(lastpg)+" 頁";
- return pagenav
複製代碼
company.html 加入
- {% if page_nav %}
- <div style="ruby-align: center">{{page_nav | safe}}</div>
- {% endif %}
複製代碼
完成
文章出處: NetYea 網頁設計, 慧晟數位科技, 網站架設
參考文章
https://stackoverflow.com/questi ... rts-to-first-option
|
|