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

时间:2018-12-27 19:46:26

标签: python flask flask-sqlalchemy

我正在尝试将变量从一种途径传递到另一种途径,但是我做不到。有人可以指导我这样做吗?我在最后一行看到错误。

@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)

1 个答案:

答案 0 :(得分:0)

问题在于代码的组织方式。函数中的变量在函数内作用域,因此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'))