32

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

在我的处理程序中,我能够收到请求

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

我得到的数据来自 str(dictionary)

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

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

4

6 回答 6

48

作为 Eloim 答案的替代方案,Tornado为“转义/取消转义 HTML、JSON、URL 和其他”提供了tornado.escape 。使用它应该会给你你想要的东西:

data = tornado.escape.json_decode(self.request.body)
于 2015-01-25T20:13:24.153 回答
22

您正在接收一个 JSON 字符串。使用 JSON 模块对其进行解码

import json

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

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

于 2013-05-10T09:02:05.223 回答
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))
于 2013-06-24T18:31:43.033 回答
0

如果您使用的是 WebApp2,它会使用自己的 json extras。(解码) 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)
于 2017-03-31T03:01:24.170 回答
0

怎么样

bind_args = dict((k,v[-1] ) for k, v in self.request.arguments.items())
于 2017-05-27T08:40:30.347 回答
-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`
于 2017-02-26T22:48:54.433 回答