为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

FFIVE 2022-05-11 15:22:05
我想使用变量“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'])
查看完整描述

1 回答

?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

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


查看完整回答
反对 回复 2022-05-11
  • 1 回答
  • 0 关注
  • 192 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号