Tornado support / json support

Does Tornado support Content-Type "application/json"

?

According to the call stack (provided stream_request_body = False

), the only method called to parse the request body is parse_body_arguments (httputil.py 662), which only accepts "application/x-www-form-urlencoded"

and"multipart/form-data"

+3


source to share


1 answer


The solution is pretty trivial. You just need to json.loads()

get the body and hope it is a proper JSON encoded dictionary (if you want, catch the exception and provide meaningful feedback). You can't expect what application/json

's in Content-Type

; during POST, which will already be application/x-www-form-urlencoded

.

Here's an example server:

import json
import tornado.httpserver
import tornado.ioloop
import tornado.web

class MyHandler(tornado.web.RequestHandler):
    def post(self):
        data = json.loads(self.request.body.decode('utf-8'))
        print('Got JSON data:', data)
        self.write({ 'got' : 'your data' })

if __name__ == '__main__':
    app = tornado.web.Application([ tornado.web.url(r'/', MyHandler) ])
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(8888)
    print('Starting server on port 8888')
    tornado.ioloop.IOLoop.instance().start()

      



You can check this using for example curl

:

curl -d '{"hello": "world"}' http://localhost:8888/

      

+5


source







All Articles