Flask 分页示例无法工作,缺少 "iter_pages
我正在做一个小的网页应用,用来查看一些日志文件。但是,我发现在查询数据库时,返回的数据量变得非常大。
我想实现一些分页功能,参考了这个例子 分页。我把类放在一个文件里,然后在Flask的视图中加载它。接着,我像这样实现了我的分页视图:
@app.route('/index/', defaults={'page':1})
@app.route('/index/page/<int:page>')
def index(page):
count = db_session.execute("select host,facility,level,msg from messages").rowcount
tblqry = db_session.execute("select host,facility,level,msg from messages").fetchmany(size=1000)
if not tblqry and page != 1:
abort(404)
pagination = Pagination(page, PER_PAGE, count)
return render_template('index.html', pagination=pagination, tblqry=tblqry)
之后,我创建了一个名为 _pagination_helper.html
的宏文件,里面放了宏的内容。然后我用以下方式导入了这个分页助手的宏:
{% from "_pagination_helper.html" import render_pagination %}
但是当我尝试做这样的事情时:
{{ render_pagination(host[0]) }}
Flask却提示:
UndefinedError: 'str object' has no attribute 'iter_pages'
那么,为什么Flask找不到'iter_pages',因为我已经在视图文件中包含了分页类呢?
另外,我也不太确定应该把“如何做”的URL生成助手放在哪里。
编辑:这是我的pagination_helper的样子:
{% macro render_pagination(pagination) %}
<div class=pagination>
{% for page in pagination.iter_pages() %}
{% if page %}
{% if page != pagination.page %}
<a href="{{ url_for_other_page(page) }}">{{ page }}</a>
{% else %}
<strong>{{ page }}</strong>
{% endif %}
{% else %}
<span class=ellipsis>…</span>
{% endif %}
{%- endfor %}
{% if pagination.has_next %}
<a href="{{ url_for_other_page(pagination.page + 1)}}">Next »</a>
{% endif %}
</div>
{% endmacro %}
1 个回答
3
你需要把一个 Pagination
对象传给这个宏,而不是一个字符串。host[0]
是一个字符串,而不是你在视图函数中创建的 pagination
值。
使用:
{{ render_pagination(pagination) }}