【问题标题】:How is json data posted?json数据如何发布?
【发布时间】:2016-01-10 05:24:42
【问题描述】:

我的flask代码如下:

@app.route('/sheets/api',methods=["POST"])
def insert():
    if request.get_json():
        return "<h1>Works! </h1>"
    else:
        return "<h1>Does not work.</h1>"

当请求是:

POST /sheets/api HTTP/1.1
Host: localhost:10080
Cache-Control: no-cache

{'key':'value'}

结果是&lt;h1&gt;Does not work.&lt;/h1&gt;

当我添加了Content-Type 标头时:

POST /sheets/api HTTP/1.1
Host: localhost:10080
Content-Type: application/json
Cache-Control: no-cache

{'key':'value'}

我收到 400 错误。

我做错了什么?

【问题讨论】:

    标签: python json http flask


    【解决方案1】:

    您没有发布有效的 JSON。 JSON 字符串使用 引号:

    {"key":"value"}
    

    带单引号的字符串不是有效的 JSON,并返回 400 Bad Request 响应。

    针对仅实现您的路由的本地 Flask 服务器的演示:

    >>> import requests
    >>> requests.post('http://localhost:5000/sheets/api', data="{'key':'value'}", headers={'content-type': 'application/json'}).text
    '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n<title>400 Bad Request</title>\n<h1>Bad Request</h1>\n<p>The browser (or proxy) sent a request that this server could not understand.</p>\n'
    >>> requests.post('http://localhost:5000/sheets/api', data='{"key":"value"}', headers={'content-type': 'application/json'}).text
    '<h1>Works! </h1>'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      • 2015-05-05
      • 2018-05-28
      • 2011-02-24
      • 2011-09-09
      • 1970-01-01
      相关资源
      最近更新 更多