我用 python 编写了一个简单的 REST-ful Web 服务器flask
以下步骤tutorial http://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask;但我打电话时遇到问题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>
我尝试调试并发现get_json
方法,传递的参数已转换为'\\'{title:Read a book}\\''
as data
and request_charset
is None
;但我不知道解决方案。有什么帮助吗?
EDIT 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
但是这次调用后出现了以下错误POST
via curl
:
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>
EDIT 2:
为了澄清,我应该提到我正在开发 64 位版本的 Microsoft Windows 7,带有 Python 版本 2.7 和最新版本的 Flask。