【发布时间】:2019-04-02 05:29:33
【问题描述】:
我想使用flask 和jquery 将字典(button_state)从javascript 传递到python。 在 jquery 方面,我有:
$(".btn#submit").click(function(event){
newdata = JSON.stringify(buttons_state);
console.log("submission button POST attempt: " + newdata)
$.ajax({
url: '/submission',
dataType: 'json',
type: 'post',
contentType: 'application/json',
data: newdata,
processData: false,
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
在服务器端:
@app.route('/submission', methods=['POST'])
def submission():
info = request.get_json(silent=False)
return info
但我收到错误 500:
Traceback (most recent call last):
File "/Users/timrand/anaconda3/lib/python3.7/site-
packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/Users/timrand/anaconda3/lib/python3.7/site-
packages/flask/app.py", line 1816, in full_dispatch_request
return self.finalize_request(rv)
File "/Users/timrand/anaconda3/lib/python3.7/site-
packages/flask/app.py", line 1831, in finalize_request
response = self.make_response(rv)
File "/Users/timrand/anaconda3/lib/python3.7/site-
packages/flask/app.py", line 1982, in make_response
reraise(TypeError, new_error, sys.exc_info()[2])
File "/Users/timrand/anaconda3/lib/python3.7/site-
packages/flask/_compat.py", line 34, in reraise
raise value.with_traceback(tb)
File "/Users/timrand/anaconda3/lib/python3.7/site-
packages/flask/app.py", line 1974, in make_response
rv = self.response_class.force_type(rv, request.environ)
File "/Users/timrand/anaconda3/lib/python3.7/site-
packages/werkzeug/wrappers.py", line 921, in force_type
response = BaseResponse(*_run_wsgi_app(response, environ))
File "/Users/timrand/anaconda3/lib/python3.7/site-
packages/werkzeug/test.py", line 923, in run_wsgi_app
app_rv = app(environ, start_response)
TypeError: 'dict' object is not callable
视图函数未返回有效响应。返回类型必须是字符串、元组、响应实例或 WSGI 可调用的,但它是一个字典。 127.0.0.1 - - [29/Oct/2018 07:53:48] “POST /signUpUser HTTP/1.1”500 -
似乎服务器代码未正确检索数据,或者 JSON.stringify 将数据转换为字符串的方式存在问题。我读过很多其他有同样问题的人,并尝试了堆栈溢出的解决方案,但只得到错误 400。
【问题讨论】:
-
如果您可以显示您的烧瓶应用程序显示的完整错误,那么可能很容易知道实际问题是什么?
-
您是否尝试过将客户端提交硬编码为有效的 JSON,或者甚至传递空字典 (
newdata="{}")。这可以帮助您确定您的问题是客户端还是服务器端。 -
newdata是一个字符串,这可能是问题吗?在get_json参数中添加force=True怎么样?
标签: javascript python jquery flask