我收到此错误:“UnboundLocalError:分配前引用的局部变量

我想使用变量“Requesting_books”,但每次我收到此错误:“UnboundLocalError: local variable 'Requesting_books' referenced before assignment”。实际上我想在我的 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'])



FFIVE
浏览 193回答 1
1回答

幕布斯7119047

您应该添加一个else块,因为如果request.method不是,则不会'POST'分配任何变量。@app.route('/request books', methods=['GET', 'POST'])@app.route('/get books', methods=['GET', 'POST'])def requesting_for_books():&nbsp; &nbsp; if request.method == 'POST':&nbsp; &nbsp; &nbsp; &nbsp; requesting = mongo.db.mylogin&nbsp; &nbsp; &nbsp; &nbsp; Requesting_books = requesting.find_one({'name' : request.form['bookname']})&nbsp; &nbsp; &nbsp; &nbsp; return render_template('get_books.html', title="Get Books", my_book=Requesting_books['name']) #<--- Move return into the if block&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; #Do something if request.method is not "POST"
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python