【问题标题】:Typerror() in python while passing parameters to the route [duplicate]python中的Typerror(),同时将参数传递给路由[重复]
【发布时间】:2019-01-07 23:55:55
【问题描述】:

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

@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 %}

【问题讨论】:

    标签: python flask


    【解决方案1】:

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

    这是因为你是这样定义它的:

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

    在烧瓶中,如果您希望视图函数采用参数,则需要将它们包含在路由中。在您的示例中,这可能如下所示:

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

    如果您没有将&lt;book_title 放入路由中,flask 将无法将book_title 参数提供给book 函数,这就是它在错误中告诉您的内容。

    【讨论】:

    • 如果我这样做,我会在 return render_template("booktitle.html",book_title=book_title) 上得到这个 werkzeug.routing.BuildError: Could not build url for endpoint 'book'. Did you forget to specify values ['book_title']?
    猜你喜欢
    • 2021-04-24
    • 2023-03-20
    • 2018-06-27
    • 2019-03-03
    • 2018-08-14
    • 2017-07-31
    • 2020-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多