我已经按照本 教程 中的步骤使用 flask
在 python 中编写了一个简单的 REST-ful Web 服务器;但我在调用 POST
请求时遇到了问题。代码是:
@app.route('/todo/api/v1.0/tasks', methods=['POST'])
def create_task():
if not request.json or not 'title' in request.json:
abort(400)
task = {
'id': tasks[-1]['id'] + 1,
'title': request.json['title'],
'description': request.json.get('description', ""),
'done': False
}
tasks.append(task)
return jsonify({'task': task}), 201
我发送一个 POST
请求使用 curl
作为上述页面中的示例:
curl -i -H "Content-Type: application/json" -X POST -d '{"title":"Read a book"}' http://127.0.0.1:5000/todo/api/v1.0/tasks
但是我得到这个错误的回应:
HTTP/1.0 400 BAD REQUEST
Content-Type: text/html
Content-Length: 187
Server: Werkzeug/0.11.10 Python/2.7.9
Date: Mon, 30 May 2016 09:05:52 GMT
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)</p>
I’ve tried to debug and I found out in the get_json
method, the passed argument has been translated to '\\'{title:Read a book}\\''
as data
and request_charset
是 None
;但我不知道解决方案。有什么帮助吗?
编辑 1:
我尝试了@domoarrigato 的回答并实现了 create_task
方法,如下所示:
@app.route('/todo/api/v1.0/tasks', methods=['POST'])
def create_task():
try:
blob = request.get_json(force=True)
except:
abort(400)
if not 'title' in blob:
abort(400)
task = {
'id': tasks[-1]['id'] + 1,
'title': blob['title'],
'description': blob.get('description', ""),
'done': False
}
tasks.append(task)
return jsonify({'task': task}), 201
但是这次我在通过 curl
调用 POST
后出现以下错误:
HTTP/1.0 400 BAD REQUEST
Content-Type: text/html
Content-Length: 192
Server: Werkzeug/0.11.10 Python/2.7.9
Date: Mon, 30 May 2016 10:56:47 GMT
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>
编辑 2:
为澄清起见,我应该提到我正在使用 64 位版本的 Microsoft Windows 7 以及 Python 2.7 版和最新版本的 Flask。
原文由 Zeinab Abbasimazar 发布,翻译遵循 CC BY-SA 4.0 许可协议
这适用于 Windows 7 64:
反斜杠和双引号。