Python json数据是如何发布的?

Python json数据是如何发布的?,python,json,http,flask,Python,Json,Http,Flask,我的烧瓶代码如下: @app.route('/sheets/api',methods=["POST"]) def insert(): if request.get_json(): return "<h1>Works! </h1>" else: return "<h1>Does not work.</h1>" 结果是不起作用 添加内容类型标题时: 我得到一个400错误 我做错了什么?您没有发布有效的J

我的烧瓶代码如下:

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

添加内容类型标题时:

我得到一个400错误


我做错了什么?

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

使用单引号时,字符串不是有效的JSON,返回400错误的请求响应

针对仅实现路由的本地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>'

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

使用单引号时,字符串不是有效的JSON,返回400错误的请求响应

针对仅实现路由的本地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>'
{"key":"value"}
>>> 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>'