我得到了这个错误:“UnboundLocalError:在赋值之前引用了局部变量'Requesting\u books'”

2024-10-06 12:51:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用变量“Requesting\u books”,但每次我都会遇到这样的错误:“UnboundLocalError:localvariable'Requesting\u 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'])

Tags: nameappgetrequest错误bookspostroute
1条回答
网友
1楼 · 发布于 2024-10-06 12:51:52

您应该添加一个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"

相关问题 更多 >