我收到此错误:“ UnboundLocalError:分配前引用了本地变量'Requesting_books'

时间:2019-08-25 10:12:26

标签: python flask

我想使用变量“ Requesting_books”,但是每次遇到此错误时:“ UnboundLocalError:分配前引用了本地变量'Requesting_books'”。实际上,我想在我的Jinja模板中使用此变量,以便可以显示搜索结果。请帮帮我!

@app.route('/request books', methods=['GET', 'POST'])
@app.route('/get books', methods=['GET', 'POST'])
def requesting_for_books():
    if request.method == 'POST':
        requesting = mongo.db.mylogin
        Requesting_books = requesting.find_one({'name' : request.form['bookname']})
    return render_template('get_books.html', title="Get Books", my_book=Requesting_books['name'])

1 个答案:

答案 0 :(得分:1)

您应该添加一个else块,因为如果request.method不是'POST',则不会分配任何变量。

@app.route('/request books', methods=['GET', 'POST'])
@app.route('/get books', methods=['GET', 'POST'])
def requesting_for_books():
    if request.method == 'POST':
        requesting = mongo.db.mylogin
        Requesting_books = requesting.find_one({'name' : request.form['bookname']})
        return render_template('get_books.html', title="Get Books", my_book=Requesting_books['name']) #<--- Move return into the if block
    else:
        #Do something if request.method is not "POST"