weixin_33721344 2020-03-29 20:48 采纳率: 0%
浏览 244

Python Tornado请求JSON

My application accepts data from POST method which I am running through JQuery's AJAX request. I am sending JSON formatted data, but in handler as I accept request and access the data it turns out to be byte string type.

I am using my_body = self.request.body method.

For example, if I am sending {"drzava":"rs","kategorija":"general"} received data looks like b'drzava=rs&kategorija=general'.

Problem is, afterwards I can't use tornado.escape.json_decode(), to make it dictionary. I keep getting the following error:

Traceback (most recent call last):
  File "/home/stefan/.local/lib/python3.6/site-packages/tornado/web.py", line 1697, in _execute
    result = method(*self.path_args, **self.path_kwargs)
  File "main.py", line 164, in post
    telo_json = tornado.escape.json_decode(telo)
  File "/home/stefan/.local/lib/python3.6/site-packages/tornado/escape.py", line 83, 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)

I will post the code, if needed.

  • 写回答

2条回答 默认 最新

  • weixin_33743880 2020-03-30 09:16
    关注

    The data you receive in your Tornado server application depends on how your data is being "packaged" by the client.

    You could have application/x-www-form-urlencoded data (seems to be your case above) which you can process in Tornado using get_body_argument:

    drzava = self.get_body_argument("drzava", None)
    kategorija = self.get_body_argument("kategorija", None)
    

    or you could have application/json (seems to be want you want):

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

    In order to send JSON data from your browser you need to actually send JSON data and specify the content type:

    var data = {"drzava":"rs", "kategorija":"general"};
    $.ajax({
        url: YOUR_URL,
        type: "POST",
        data: JSON.stringify(data),
        contentType: "application/json",
        ...
    

    EDIT:
    In the end the issue was that the HTML page was sending the data using a form and would not actually use the JS code.

    评论

报告相同问题?

悬赏问题

  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系