如何修复“index()缺少1个必需的位置参数:“page”?

2024-09-29 08:19:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在我的网站排序功能,我有这个问题。 这是我的密码:

@app.route("/", defaults={'page':0, 'type':'top'})
@app.route("/<type>")
@app.route('/page/<int:page>')
def index(type, page):
    perpage=5
    startat=page*perpage
    cur = mysql.connection.cursor()
    if type=='top':
        cur.execute("SELECT * FROM posts LIMIT %s, %s ORDER BY upvotes ASC", (startat,perpage))
        data = cur.fetchall()
        cur.close()
        return render_template("index.html", dat=data)
    elif type=='new':
        cur.execute("SELECT * FROM posts LIMIT %s, %s ORDER BY created_at ASC", (startat,perpage))
        data = cur.fetchall()
        cur.close()
        return render_template("index.html", dat=data)

那么问题出在哪里呢

PS:对于按功能排序和分页,这是一种好方法吗?如果不是,那么最好的方法是什么

谢谢


Tags: fromappexecutedataindextoptypepage
1条回答
网友
1楼 · 发布于 2024-09-29 08:19:02

可以在不定义类型或页面的情况下访问index()

  • 如果您转到/t,那么您正在呼叫index(type="t")。在本例中,您没有指定page
  • 如果您转到/page/p,则您正在呼叫index(page="p")。在本例中,您没有指定type

因为函数本身没有这些参数的默认值,所以它会抛出一个错误。这里的简单解决方案是,不要将默认值放在@app.route("/"),而是将它们放在函数头本身中:

@app.route("/")
@app.route("/<type>")
@app.route('/page/<int:page>')
def index(type="top", page=0):
    ...

如果指定了<type><page>,这些默认值将被覆盖

相关问题 更多 >