Flask:request.json有效,但request.get_json()导致错误代码500

时间:2013-07-05 01:01:43

标签: python flask

documentation表示要使用request.get_json(),但这会导致服务返回错误:

Server returned HTTP response code: 500
但是,

调用request.datarequest.json都有效。

堆栈追踪:

Traceback (most recent call last):
  File "/home/blake/ves/p27/lib/python2.7/site-packages/flask/app.py", line 1701, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/blake/ves/p27/lib/python2.7/site-packages/werkzeug/contrib/fixers.py", line 125, in __call__
    return self.app(environ, start_response)
  File "/home/blake/ves/p27/lib/python2.7/site-packages/flask/app.py", line 1689, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/home/blake/ves/p27/lib/python2.7/site-packages/flask/app.py", line 1687, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/blake/ves/p27/lib/python2.7/site-packages/flask/app.py", line 1360, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/blake/ves/p27/lib/python2.7/site-packages/flask/app.py", line 1358, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/blake/ves/p27/lib/python2.7/site-packages/flask/app.py", line 1344, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/blake/workspace/starcycle-flask/starcycleweb.py", line 17, in api
    print request.get_json()
  File "/home/blake/ves/p27/lib/python2.7/site-packages/werkzeug/local.py", line 336, in __getattr__
    return getattr(self._get_current_object(), name)
AttributeError: 'Request' object has no attribute 'get_json'

我认为get_json是获取json数据的首选方式。

2 个答案:

答案 0 :(得分:10)

在Flask / wrappers.py中,方法get_json()被定义为类Request的方法。

但是,同一文件仍包含旧的,已弃用的方法json()。如果您有旧版本的烧瓶,则a)更新或b)改为使用request.json()

答案 1 :(得分:4)

我对flask Response对象有类似的错误,它最终是一个版本问题,我们使用了flask 0.12.1,而get_json()在1.0.2上可用

文档:

http://flask.pocoo.org/docs/0.12/api/#response-objects

VS

http://flask.pocoo.org/docs/1.0/api/#response-objects