Tornado request.body

2019-04-18 09:26发布

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.

6条回答
Fickle 薄情
2楼-- · 2019-04-18 10:05

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`
查看更多
▲ chillily
3楼-- · 2019-04-18 10:06

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)
查看更多
你好瞎i
4楼-- · 2019-04-18 10:06

how about

bind_args = dict((k,v[-1] ) for k, v in self.request.arguments.items())
查看更多
5楼-- · 2019-04-18 10:11

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

查看更多
女痞
6楼-- · 2019-04-18 10:15

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)
查看更多
迷人小祖宗
7楼-- · 2019-04-18 10:17

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))
查看更多
登录 后发表回答