Skip to content Skip to sidebar Skip to footer

Tornado Has Correct Request Body, But Cannot Find Correct Arguments

Making a pretty straightforward Tornado app, but something that seems impossible is happening based on my understanding of Tornado. In short I've got the following RequestHandler:

Solution 1:

get_body_argument is intended for form-encoded data, as you have discovered. Tornado has little support built-in for JSON data in request bodies. You can simply:

import json


classCreateUserHandler(tornado.web.RequestHandler):
    defpost(self):
        data = json.loads(self.request.body)
        print data.get("email")

Solution 2:

Here's a little helper method I've been adding to my handlers in order to retrieve all of the body arguments as a dict:

from tornado.web import RequestHandler
from tornado.escape import json_decode

classCustomHandler(RequestHandler):

    defget_all_body_arguments(self):
        """
        Helper method retrieving values for all body arguments.

        Returns:
            Dict of all the body arguments.
        """if self.request.headers['Content-Type'] == 'application/json':
            return json_decode(self.request.body)
        return {arg: self.get_body_argument(arg) for arg in self.request.arguments}

Solution 3:

Not sure why this is the case, but I found a resolution. It required both url-encoding the body (this seems very strange to me as it's a request payload), and changing the Content-Type header to application/x-www-form-urlencoded

This is the new output of the script above:

email=slater%40indico.io&password=password
slater@indico.io

Post a Comment for "Tornado Has Correct Request Body, But Cannot Find Correct Arguments"