龙卷风请求。体

时间:2013-05-08 23:03:56

标签: python python-2.7 tornado

我的Tornado应用程序通过http正文请求接受POST数据

在我的处理程序中,我能够获得请求

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

我得到的数据来自str(字典)

有没有办法以Python字典的形式接收这些数据?

我不想在服务器端使用eval将此字符串转换为Python字典。

6 个答案:

答案 0 :(得分:38)

作为Eloim答案的替代方案,Tornado提供了tornado.escape来逃避/取消HTML,JSON,URL和其他内容"。使用它应该准确地给你你想要的东西:

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

答案 1 :(得分:17)

您正在接收JSON字符串。 使用JSON模块解码它

import json

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

了解更多信息:http://docs.python.org/2/library/json.html

答案 2 :(得分:1)

我认为在解析Tornado中的请求时遇到了类似的问题。尝试使用urllib.unquote_plus模块:

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


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

我的代码必须为不同格式的请求做好准备,所以我做了类似的事情:

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

答案 3 :(得分:0)

如果您使用的是WebApp2,它会使用自己的json附加功能。 (解码) 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)

例如,我的帖子密钥是' postvalue'

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

答案 4 :(得分:0)

怎么样

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

答案 5 :(得分:-1)

我在内置龙卷风时解析身体的最佳方法httputil
多输入(如复选框,表格等)的好工作。 如果提交元素在字典返回值列表中具有相同的名称。

工作样本:

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`