Flask字典应用POST请求报错:TypeError: 'method' object is not subscriptable解决求助
问题分析与解决方案
这个错误是个很典型的Python语法问题,一眼就能定位到根源——你把方法调用当成字典来直接访问了!
错误根源
request.get_json是Flask提供的一个方法(function),要获取请求里的JSON数据,必须先通过括号()调用它来得到字典对象。但你在add_word函数里错误地用了下标[]去直接访问方法本身:
word = request.get_json['word'] # 错误:get_json是方法,不是字典 meaning = request.get_json['meaning'] # 同样错误
这就触发了TypeError: 'method' object is not subscriptable——Python不允许对方法对象使用下标操作。
修复后的add_word函数
而且你已经把get_json()的调用结果存在了req变量里,直接复用这个变量就好,没必要重复调用方法:
@app.route('/word', methods=['POST']) def add_word(): req = request.get_json() # 正确调用方法,拿到JSON数据字典 # 从已获取的字典中提取数据 word = req['word'] meaning = req['meaning'] conn = mysql.get_db() cur = conn.cursor() cur.execute('insert into word(word, meaning) VALUES (%s, %s)', (word, meaning)) conn.commit() cur.close() return json.dumps('success')
额外注意事项(前端+其他小问题)
前端请求格式验证
要确保你的前端AJAX请求正确发送JSON格式数据,并且设置Content-Type: application/json请求头。比如处理表单提交的JS代码应该类似这样:document.getElementById('word-form').addEventListener('submit', function(e) { e.preventDefault(); const word = document.getElementById('word').value; const meaning = document.getElementById('meaning').value; fetch('/word', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ word, meaning }), }) .then(res => res.json()) .then(() => { alert('单词添加成功!'); location.reload(); // 刷新页面更新词库列表 }) .catch(err => console.error('添加失败:', err)); });如果前端没设置这个请求头,
request.get_json()会返回None,你会遇到新的NoneType下标错误。index函数的小问题
你在index函数的SQL执行语句里,参数(user_input)不是元组(括号只是优先级符号),要改成带逗号的(user_input,),否则可能触发SQL参数绑定错误:cur.execute('select meaning from word where word=%s', (user_input,) ) # 注意末尾的逗号
内容的提问来源于stack exchange,提问作者William Pepple
相关产品推荐
相关产品推荐

