Python中的烧瓶分页帮助

时间:2019-11-21 10:50:27

标签: python mysql flask pagination

我正在尝试在HTML中创建一个按钮,单击该按钮后将转到下一页/上一页。我已经尝试过分页和小便,但似乎没有使其工作。

这是我的应用程序:

from flask import Flask,render_template, request, json
from flask_mysqldb import MySQL
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'example'
app.config['MYSQL_USER'] = 'example'
app.config['MYSQL_PASSWORD'] = 'example'
app.config['MYSQL_DB'] = 'fund_raiser'
mysql = MySQL(app)

@app.route('/funds/pages/', defaults={'page':0})
@app.route('/funds/pages/<int:page>')
def fund_pages(page):
    perpage = 5
    first_page = page*perpage
    cur = mysql.connection.cursor()
    cur.execute("select * from fund_table limit "+str(first_page)+", "+str(perpage)+";", mysql.connection.commit())
    data = cur.fetchall()
    return render_template('funds.html', data=data)

我在HTML页面的哪里添加href标记?正确的变量是什么?

1 个答案:

答案 0 :(得分:2)

使用url_for()函数非常容易。
您可以为路由调用函数的名称,并将其传递给变量。

href="{{ url_for('fund_pages', page=page_num) }}"

page_num是页码。

要动态获取页码,可以简单地从当前页码加减1。例如,您可以存储page_prev = current_page - 1page_next = current_page + 1

您可以将这些变量作为url_for参数传递给page函数。

示例:

# in fund_pages()
prev_page = page - 1
next_page = page + 1
return render_template('template.hmtl', next_page=next_page, prev_page=prev_page)

# in the template
<a href="{{ url_for('fund_pages', page=prev_page) }}">Previous</a>
<a href="{{ url_for('fund_pages', page=next_page) }}">Next</a>