Tornado request.body

2019-04-18 09:39发布

问题:

My Tornado application accepts POST data through http body request

In my handler I am able to get the request

def post(self):
    data = self.request.body

The data I am getting is in the from of str(dictionary)

Is there a way to receive this data in the form of a Python dictionary?

I don't want to use eval on the server side to convert this string to a Python dictionary.

回答1:

As an alternative to Eloim's answer, Tornado provides tornado.escape for "Escaping/unescaping HTML, JSON, URLs, and others". Using it should give you exactly what you want:

data = tornado.escape.json_decode(self.request.body)


回答2:

You are receiving a JSON string. Decode it with the JSON module

import json

def post(self):
    data = json.loads(self.request.body)

For more info: http://docs.python.org/2/library/json.html



回答3:

I think I had a similar issue when I was parsing requests in Tornado. Try using the urllib.unquote_plus module:

import urllib
try:
    import simplejson as json
except ImportError:
    import json


data = json.loads(urllib.unquote_plus(self.request.body))

My code had to be prepared for both different formats of request, so I did something like:

try:
    json.loads(self.request.body)
except:
    json.loads(urllib.unquote_plus(self.request.body))


回答4:

If you are using WebApp2, it uses its own json extras. (Decode) http://webapp2.readthedocs.io/en/latest/_modules/webapp2_extras/json.html

    data = json.decode(self.request.body)
    v = data.get(key)   
    self.response.write(v)

For example my post key is 'postvalue'

    data = json.decode(self.request.body)
    v = data.get('postvalue')   
    self.response.write(v)


回答5:

how about

bind_args = dict((k,v[-1] ) for k, v in self.request.arguments.items())


回答6:

Best way for me to parse body in tornado built-in httputil
Good work with multi input (like checkbox, tables, etc.). If submit elements have same name in dictionary returning list of values.

Working sample:

import tornado.httputil    

    def post(self):
        file_dic = {}
        arg_dic = {}

        tornado.httputil.parse_body_arguments('application/x-www-form-urlencoded', self.request.body, arg_dic, file_dic)

    print(arg_dic, file_dic)  # or other code`