一个适用于python下django开发的分页函数
[Copy to clipboard] [ - ]
CODE:
#coding=gb18030
#分页函数
#参数表 page_no:当前页码 sql:数据库查询语句(不包含order by部分) page_str:当前页下带的get参数与值 per:每页的记录数 midnum:显示多少页的页码
from django.db import connection
import re
import math
def page(page_no=1,sql='',page_str='',per=10,midnum=10):
page_no=int(page_no)
if page_str>='':
page_str='?'+str(page_str)+'&'
else:
page_str='?'
reobj= re.compile(r'(?<=select).+?(?=from)')
result= reobj.sub(' count(*) ', sql)
cursor = connection.cursor()
cursor.execute(result)
row=cursor.fetchone()
if row[0]>=1:
total=row[0]
else:
return 'dff'
page_conunt=total/per+1 #页数统计
page_code='<table><tr><td>' #分页表格html代码
if page_no>=page_conunt:
page_no=page_conunt
next_page=page_no+1
prev_page=page_no-1
offset=math.floor(midnum/2)
current_page=page_no
if current_page-offset<=0:
current_page=offset+1
if current_page+offset>page_conunt:
current_page=page_conunt-offset
if current_page-offset >0:
begin=current_page-offset
else:
begin=1
if current_page+offset <page_conunt:
end=current_page+offset
else:
end=page_conunt
if page_conunt==1:
return {'page':'共'+str(total)+'笔结果.'}
else:
page_code+='共'+str(page_conunt)+'页,'+str(total)+'笔结果.</td><td>'
if page_no>1:
page_code+=' <a href="'+str(page_str)+'page=1">首页</a> <a href="'+page_str+'page='+str(prev_page)+'">«上页</a>'
for i in range(begin,end+1):
if page_no==i:
page_code+=' <font color=red>'+str(i)+'</font>'
else:
page_code+=' <a href="'+page_str+'page='+str(i)+'">'+str(i)+'</a>'
if page_no<page_conunt:
page_code+=' <a href="'+page_str+'page='+str(next_page)+'">下页»</a> <a href="'+page_str+'page='+str(page_conunt)+'">末页</a>'
page_code+=' </td></tr></table>'
mbegin=(page_no-1)*per
mend=page_no*per
if(mbegin<0):mbegin=0
if(mend>total):mend=total
sql+=' limit '+str(mend-mbegin)+','+str(mbegin)
return {'page':page_code,'sql':sql}
刚写完的,测试了一遍没错了
分页的格式比较实用如下:
共3页,5笔结果. 首页 «上页 1 2 3 下页» 末页