简体   繁体   中英

Flask: request.json works but request.get_json() causes error code 500

The documentation says to use request.get_json() , but that causes the service to return an error:

Server returned HTTP response code: 500

calling request.data or request.json both work, however.

Stack trace:

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'

I thought get_json is was the preferred way to get the json data.

In Flask/wrappers.py the method get_json() is defined as method to the class Request .

However, the same file still contains the old, deprecated method json() . If you have an old version of flask, then a) update or b) use request.json() instead.

I had similar error with the flask Response object, it ended up being a version issue, we used flask 0.12.1 and get_json() is available on 1.0.2

Docs:

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

VS

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM