Old*_*zer 1 python json http flask
我的flask
代码如下:
@app.route('/sheets/api',methods=["POST"])
def insert():
if request.get_json():
return "<h1>Works! </h1>"
else:
return "<h1>Does not work.</h1>"
Run Code Online (Sandbox Code Playgroud)
当请求是:
POST /sheets/api HTTP/1.1
Host: localhost:10080
Cache-Control: no-cache
{'key':'value'}
Run Code Online (Sandbox Code Playgroud)
结果是<h1>Does not work.</h1>
.
当我添加Content-Type
标题时:
POST /sheets/api HTTP/1.1
Host: localhost:10080
Content-Type: application/json
Cache-Control: no-cache
{'key':'value'}
Run Code Online (Sandbox Code Playgroud)
我收到400错误.
我究竟做错了什么?
您没有发布有效的JSON.JSON字符串使用双引号:
{"key":"value"}
Run Code Online (Sandbox Code Playgroud)
使用单引号时,字符串无效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>'
Run Code Online (Sandbox Code Playgroud)