我通过以下代码获取python中的项目列表:
from flask_paginate import Pagination
@app.route('/retrieve_data')
def retrieve():
PER_PAGE=5
connection = MongoClient()
db=connection.rheoML
fs = gridfs.GridFS(db)
search = False
q = request.args.get('q')
if q:
search = True
try:
page = int(request.args.get('page', 2))
except ValueError:
page = 1
List=fs.list()
pagination = Pagination(page=page,per_page=PER_PAGE, total=len(List), search=search, record_name='List')
return render_template("retrieveFile.html",List=List,fs=fs,form="submitIt",pagination=pagination,)
我在https://pythonhosted.org/Flask-paginate/关注教程 我还在retrieveFile.html中执行以下操作以适应分页:
<form id="submitIt" name="submitIt" action="/GetFile" method="Post" onsubmit="return validate(this)">
{{ pagination.info }}
<table>
<tr>
<th>Select</th><th>Filename</th><th>Operator</th>
</tr>
{% for file in List %}
<tr>
<td>
<input type="checkbox" name="FileName" value={{file.strip('u').strip("'")}}><br>
</td>
<td>
<name="FileName1" id="file" value={{file.strip('u').strip("'")}}>{{file.strip('u').strip("'")}}<br>
</td>
<td>
{{fs.get_last_version(file).Operator}}<br>
</td>
</tr>
{% endfor %}
</table>
{{ pagination.links }}
<input type="submit" value="Download">
</form>
我在我的样式标签中添加了这个
<style>
.pagination-page-info {
padding: .6em;
padding-left: 0;
width: 40em;
margin: .5em;
margin-left: 0;
font-size: 12px;
}
.pagination-page-info b {
color: black;
background: #6aa6ed;
padding-left: 2px;
padding: .1em .25em;
font-size: 150%;
}
</style>
问题是当页面显示时,页面没有问题,但所有项目都显示在一个页面本身。请帮助我,我仍然是分页的初学者,仍然在尝试解决问题
答案 0 :(得分:2)
排序好了 只需要编辑
try:
page = int(request.args.get('page', 1))
except ValueError:
page = 1
List=fs.list()
i=(page-1)*PER_PAGE
List1=List[i:i+5]
pagination = Pagination(page=page,per_page=PER_PAGE, total=len(List), search=search, record_name='List')
return render_template("retrieveFile.html",List=List1,fs=fs,form="submitIt",pagination=pagination,)
答案 1 :(得分:2)
这里的超级答案,但希望这澄清:
除了捕获页面和per_page值之外,还需要偏移量以帮助正确显示每个页面上的结果。实际上有一个方便built-in来设置这三个,您可以使用from flask_paginate import get_page_args
导入。以下是完整的view.py代码:
from flask_paginate import Pagination, get_page_args
@search.route('/retrieve_data')
def retrieve():
# get_page_arg defaults to page 1, per_page of 10
page, per_page, offset = get_page_args()
# After the main query, you need to apply the per_page limit and offset
fs = gridfs.GridFS(db)
fs_for_render = fs.limit(per_page).offset(offset)
#you can also add css_framework='bootstrap3' to Pagination for easy styling
pagination = Pagination(page=page, per_page=per_page, offset=offset,
total=fs.count(), record_name='List')
return render_template('retrieveFile.html', fs=fs_for_render, pagination=pagination,
form="submitIt")