34

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.

9
  • It's probably a JSON string.
    – Blender
    May 8, 2013 at 23:04
  • Is there a way to convert this json string to python dictionary without using eval.
    – Joel James
    May 8, 2013 at 23:07
  • This json string involves spaces which does not other json libraries to con ver it into python dictionar
    – Joel James
    May 8, 2013 at 23:08
  • Can you post a sample?
    – Blender
    May 8, 2013 at 23:08
  • { \n \"_id\" : \"cd4cca2_9vg5jyuwqxgmxfr\", \n \"time\" : '2012-01-01', \n \"opening_type\" : \"Recall\", \n }"
    – Joel James
    May 8, 2013 at 23:17

6 Answers 6

53

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)
1
  • 2
    This doesn't work for me - I receive the error: in json_decode return json.loads(to_basestring(value)) File "/usr/lib/python3.6/json/__init__.py", line 354, in loads return _default_decoder.decode(s) File "/usr/lib/python3.6/json/decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python3.6/json/decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
    – Charlie
    Oct 22, 2018 at 10:27
23

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
  • 14
    in Python3 you have to decode the original bytestring, for eg. json.loads(self.request.body.decode('utf-8'))
    – 3k-
    Apr 17, 2014 at 11:35
  • 2
    You can now use tornado.escape.json_decode(self.request.body) which will handle all the decoding for you.
    – Will S
    Nov 21, 2016 at 11:55
  • Note that using tornado.escape wrappers to json.loads means you will be unable to customize/override JSONDecoder with cls or parse_... kwargs. (This is way more of an issue with using the complementary tornado.escape.json.encode that wraps json.dumps. but is still worth mentioning here.)
    – cowbert
    Jan 16, 2018 at 0:14
1

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))
3
  • I'm curious as to what the answer was, so let me know if this helped (or if you figured it out in chat). I'm almost positive that it was because it was url-encoded.
    – Mitch
    Jun 24, 2013 at 18:35
  • Escaping helped me here. Aug 15, 2014 at 20:55
  • 1
    For python3, it's urllib.parse.unquote_plus() May 13, 2015 at 1:47
0

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)
0

how about

bind_args = dict((k,v[-1] ) for k, v in self.request.arguments.items())
2
  • 1
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. May 27, 2017 at 11:01
  • Or { k : v[-1] for k, v in self.request.arguments.items() }
    – Jeppe
    Feb 9, 2020 at 11:35
-1

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`
1
  • this is exactly what I was looking for, thank you.
    – royce3
    Aug 12 at 23:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.