【发布时间】:2016-09-28 03:40:39
【问题描述】:
我在 python 中使用flask 编写了一个简单的 REST-ful Web 服务器,遵循此tutorial 中的步骤;但我在调用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
我使用curl作为上述页面中的示例发送POST请求:
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}\\'',因为data 和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:
为了澄清,我应该提到我正在使用 Python 2.7 版和最新版本的 Flask 开发 64 位版本的 Microsoft Windows 7。
【问题讨论】:
标签: python json flask webserver flask-restful