为什么我得到的是<built-in method title of str object at 0x7fb554f9f238>而不是值?

6

我正在尝试从book_title中检索title属性,但我得到的是<built-in method title of str object at 0x7fb554f9f238>。我已经将book_title作为参数传递给了路由book,并在booktitle.html中分配了相应的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/<book_title>/',methods=['GET','POST'])
def book(book_title):
    if request.method == 'GET':
        return render_template("individualbook.html",book_title=book_title)

这些是 booktitle.htmlindividualbook.html 的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_title=book_title) }}">
                {{ book.title }} 


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

{% endblock %}

individualbook.html

{% extends "layout.html" %}

{% block title %}
    Book
{% endblock %}

{% block body %}
    <h1>Book Details</h1>

    <ul>

        <li>Title: {{ book_title.title }}</li>
        <li>author: {{ book_title.author }}</li>
        <li>isbn: {{ book_title.isbn }}</li>

    </ul>

{% endblock %}

当我尝试获取titleauthorisbn的值时,我得到了Title:<built-in method title of str object at 0x7fb554f9f238>,而authorisbn的值为空。

你没有使用任何ORM;从调用db.execute()返回的东西只是一个元组列表,它不是一个带有字段属性的对象。title只是字符串类上的一个方法名称。 - Daniel Roseman
那么我该如何解决这个问题? - Sharik Sid
1
book_title只是一个字符串,没有内置方法。 - tomasantunes
2个回答

1
你刚刚输入了 | book_title.title |,但应该是 | book_title.title() |。 我猜当你加上括号时它会起作用...

0
  • 在路由 app.btitle 中,传递给 render_templatebook_title 变量明确赋值为数据库响应对象,这些对象可能会正确响应属性解析。

  • 在路由 app.book(individualbook.html)中,book_title 是基于请求数据和路由注释设置的函数/路由的参数。这种变量是 str 类型,没有任何属性如 .author.isbn。这里的巧合是,Python3 的 str 有一个 title 方法(见 pydoc3 str.title),因此导致模板输出不符合预期。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接