Flask报错UnboundLocalError:无法访问局部变量'request'的解决方法
错误原因与解决方案
核心问题
错误UnboundLocalError: cannot access local variable 'request' where it is not associated with a value的根本原因是变量名冲突:
在send_request函数中,你将本地变量命名为request(request = MatchRequest(...)),这会覆盖Flask提供的全局request对象。Python解释器在函数内优先查找本地变量,导致开头调用request.data时,本地的request还未赋值,从而抛出错误。
修复步骤
1. 修改变量名(关键)
将send_request函数中的request变量名替换为其他名称,比如new_match_request:
@views.route('/match_request', methods=['POST']) @login_required def send_request(): global currentBusinessID company = json.loads(request.data) companyId = company['requestCompID'] company = Company.query.get(companyId) requestMatchCompanyID = company sender_id = currentBusinessID.id receiver_id = requestMatchCompanyID.id if sender_id and receiver_id: # 修改变量名,避免覆盖全局request new_match_request = MatchRequest(sender_id=sender_id, receiver_id=receiver_id) db.session.add(new_match_request) db.session.commit() return jsonify({}) else: return jsonify({'error': 'Invalid data'}), 400
2. 优化请求头(可选但推荐)
你的JS fetch请求没有设置Content-Type: application/json,虽然用json.loads(request.data)能解析,但更规范的做法是添加请求头,同时可以直接使用Flask的request.json简化代码:
function modifyCompany(id) { fetch('/profile', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ compID: id}) }).then((_res) => { window.location.href = "/profile" })} function matchRequest(comp_id) { fetch('/match_request', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ requestCompID: comp_id }) }).then((_res) => { window.location.href = "/profile" })}
对应的Flask代码可以简化为:
# companyID函数中 company = request.json companyId = company['compID'] # send_request函数中 company = request.json companyId = company['requestCompID']
3. 避免使用全局变量(可选)
全局变量currentBusinessID在多用户场景下会出现数据冲突,建议改用Flask的session来存储用户当前选中的企业ID:
# 设置session session['current_business_id'] = companyId # 获取session中的ID sender_id = session.get('current_business_id')
内容的提问来源于stack exchange,提问作者Dre1n
相关产品推荐
相关产品推荐

