gpt4 book ai didi

python - 如何将变量传递到 FLASK 中的另一条路线

转载 作者:行者123 更新时间:2023-12-05 05:13:07 25 4
gpt4 key购买 nike

我试图将一个变量从一条路径传递到另一条路径,但我做不到。有人可以指导我这样做吗?我在最后一行收到错误。

@app.route("/search", methods=['GET', 'POST'])
def search():

if request.method == 'GET':

return render_template('search.html', navbar=True)

else:

query = request.form.get('query').lower()
query_like = '%' + query + '%'

books = db.execute('SELECT * FROM books WHERE (LOWER(isbn) LIKE :query) OR (LOWER(title) LIKE :query) '
'OR (LOWER(author) LIKE :query)',
{'query': query_like}).fetchall()

if not books:
return render_template('error.html', message='No Books were Found!', navbar=True)

return render_template('books.html', query=query, books=books, navbar=True)

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

return render_template('books.html', query=query, books=books)

最佳答案

问题在于您的代码组织方式。函数中的变量在函数内作用域,因此books 不能从第二条路径获得。除此之外,您还有一个命名冲突,其中 books=books 指的是函数本身(在模块范围内定义)。

如果你想在路由之间共享代码,把它放在一个单独的函数中:

def get_books(query, show_nav_bar=False):
query = query.lower()
query_like = '%' + query + '%'
books = db.execute('SELECT * FROM books WHERE (LOWER(isbn) LIKE :query) OR (LOWER(title) LIKE :query) '
'OR (LOWER(author) LIKE :query)', {'query': query_like}).fetchall()

if not books:
return render_template('error.html', message='No Books were Found!', navbar=True)

return render_template('books.html', query=query, books=books, navbar=show_nav_bar)


@app.route("/search", methods=['GET', 'POST'])
def search():
if request.method == 'GET':
return render_template('search.html', navbar=True)

else:
return get_books(request.form.get('query'), show_nav_bar=True)


@app.route("/books", methods=['GET', 'POST'])
def books():
return get_books(request.form.get('query'))

关于python - 如何将变量传递到 FLASK 中的另一条路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53950115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com