在python中将参数传递给rou时使用Typerror()

2024-04-18 23:54:34 发布

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

我需要使用url_for()函数和redirect()将参数传递给routes,我想我也是这么做的。但是,我得到了TypeError: book() missing 1 required positional argument: 'book_title'我知道参数book_title没有被我的代码中的book()函数接收到,这就是错误的原因。但是,我不知道幕后到底出了什么问题。 这是我的路线

@app.route('/search/<title>/',methods=['GET','POST'])
def btitle(title):
    book_title = db.execute("SELECT title,author,isbn from books WHERE (title LIKE :title)",params={"title":title}).fetchall()
    if request.method == 'GET':
        #book_title = db.execute("SELECT title,author,isbn from books WHERE (title LIKE :title)",params={"title":title}).fetchall()
        if book_title:
            return render_template("booktitle.html",book_title=book_title)
        else:
            return render_template("error.html")
    else:
        #book_title = db.execute("SELECT title,author,isbn from books WHERE (title LIKE :title)",params={"title":title}).fetchall()
        if book_title:
            return redirect(url_for("book",book_title=book_title))

@app.route('/books',methods=['GET','POST'])
def book(book_title):
    if request.method == 'GET':
        return render_template("individualbook.html",book_title=book_title)

这是我的booktitle.html

{% extends "layout.html" %}
{% block title %}
    {{ book }}
    {% endblock %}

{% block body %}
    <h1>Search results</h1>
    <ul>
    {% for book in book_title %}
        <li>
            <a href="{{ url_for('book') }}">
                {{ book }} 


            </a>
        </li>
    {% endfor %}
    </ul>

{% endblock %}

Tags: fromurlforexecutedbgetreturnif
1条回答
网友
1楼 · 发布于 2024-04-18 23:54:34

问题是book路由没有得到它所期望的参数book_title。你知道吗

这是因为您这样定义它:

@app.route('/books',methods=['GET','POST'])
def book(book_title)

在flask中,如果希望视图函数获取参数,则需要在路由中包含这些参数。在您的示例中,可以如下所示:

@app.route('/books/<book_title>',methods=['GET','POST'])
def book(book_title)

如果不将<book_title放在路由中,flask将无法向book_title函数提供book参数,这是它在错误中告诉您的。你知道吗

相关问题 更多 >