如何在web.py中实现列表结果的分页
我正在使用 Python 的 web.py
来设计一个小型网页应用,其实我并没有使用任何数据库来获取结果或记录,我会有一份记录列表(这些记录我会根据需要从某个地方获取 :))。
下面是我的代码:
code.py
import web
from web import form
urls = (
'/', 'index',
'/urls', 'urls_result',
)
app = web.application(urls, globals())
render = web.template.render('templates/')
class index:
def GET(self):
return render.home()
def POST(self):
result_list = [('Images', 'http://www.google.co.in/imghp?hl=en&tab=wi'),
('Maps', 'http://maps.google.co.in/maps?hl=en&tab=wl'),
('Play', 'https://play.google.com/?hl=en&tab=w8'),
('YouTube', 'http://www.youtube.com/?gl=IN&tab=w1'),
('News', 'http://news.google.co.in/nwshp?hl=en&tab=wn'),
('Gmail', 'https://mail.google.com/mail/?tab=wm'),
('Drive', 'https://drive.google.com/?tab=wo'),
('More»', 'http://www.google.co.in/intl/en/options/'),
('Web History', 'http://www.google.co.in/history/optout?hl=en'),
('Settings', 'http://www.google.co.in/preferences?hl=en'),
('Sign in', 'https://accounts.google.com/ServiceLogin?hl=en&continue=http://www.google.co.in/'),
('Advanced search', 'http://www.google.co.in/advanced_search?hl=en-IN&authuser=0'),
..............
..............
.............. so on until 200 records ]
return render.recordslist(result_list)
if __name__ == "__main__":
app.run()
home.html
$def with()
<html>
<head>
<title>Home Page</title>
<body alink="green" link="blue" >
<div class="main">
<center>
<form method="POST" action='urls'>
<input class="button" type="submit" name="submit" value="Submit" />
</form>
</center>
</div>
</body>
</html>
recordslist.html
$def with(result_list)
<html>
<head>
<title>List of records</title>
</head>
<body>
<table>
$for link in result_list:
<tr>
<td>$link[0]</td>
<td>$link[1]</td>
</tr>
</table>
</body>
从上面的代码来看,当我启动服务器并在浏览器中输入 web.py
返回的 IP 地址时,它会重定向到主页(网址是 /
,模板是 home.html
),这个主页上有一个包含单个按钮的表单。
在这里,我并没有使用任何 数据库
来获取记录,而是直接写死了一些记录,这些记录以 元组列表
的形式存在,如上所示。
所以,当用户点击提交按钮时,我会通过跳转到 /url
来显示这些记录,渲染的模板是 recordslist.html
,以表格的形式展示记录。
现在这个过程运行得很好。但是这里的 元组列表/记录
可能会有 200 个或更多
,所以我想为 /url
页面实现 分页
。
我在网上搜索了很多,找到的都是关于从数据库中获取记录的内容,而不是从列表中获取的,我真的很困惑,不知道怎么把结果分页,每页显示 10 条记录
。
所以有没有人能告诉我,如何从上面的代码中的列表中对结果/记录进行分页呢?
1 个回答
1
获取页面
首先,你需要从用户的请求中提取出页面信息。假设你会使用一个叫做“页面”的查询参数,你可以用它来确定当前的页面号码:
params = web.input()
page = params.page if hasattr(params, 'page') else 1
使用页面
一旦你得到了页面,分页的工作就是返回一部分结果。下面这个函数应该能帮你获取所需的结果部分(假设页面是从1开始计数的):
def get_slices(page, page_size=10):
return (page_size * (page - 1), (page_size * page)
这个函数会返回你可以用来切分结果列表的上下限。所以在你现在的代码中,如果你用的是 return render.recordslist(result_list)
,你可以改成:
lower, upper = get_slices(page)
return render.recordslist(result_list[lower:upper])