2016-11-04 32 views
0

我在教程here之后,我正在开始设置create_task函数。我不断收到Windows上的错误在Flask中构建REST API在尝试发出POST请求时收到400错误

<!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> 

我使用卷曲命令

curl -i -H "Content-Type: application/json" -X POST -d '{"title":"Read a book"}' http://localhost:5000/api/v1.0/tasks 

这里是我的代码

#!flask/bin/python 
from flask import Flask, jsonify, abort, make_response, request 

app = Flask(__name__) 

tasks = [ 
    { 
     'id': 1, 
     'title': u'Buy groceries', 
     'description': u'Milk, Cheese, Pizza, Fruit, Tylenol', 
     'done': False 
    }, 
    { 
     'id': 2, 
     'title': u'Learn Python', 
     'description': u'Need to find a good Python tutorial on the Web', 
     'done': False 
    } 
    ] 

@app.errorhandler(404) 
def not_found(error): 
    return make_response(jsonify({'404': 'Resource Not Found'}), 404) 

@app.route('/api/v1.0/tasks/<int:task_id>', methods=['GET']) 
def get_task(task_id): 
    task = [task for task in tasks if task['id'] == task_id] 
    if len(task) == 0: 
     abort(404) 
    return jsonify({'task': task[0]}) 

@app.route('/api/v1.0/tasks', methods=['POST']) 
def create_task(): 
    if not request.json or not 'title' in request.json: 
     abort(404) 
    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 

if __name__ == '__main__': 
    app.run() 

我用尽了一切我能想到的。任何帮助将不胜感激。

+2

我不能重现此。我复制粘贴此代码,并能够成功POST和GET。我甚至还复制了curl命令。 – idjaw

回答

0

你的代码工作得很好。尝试重新安装烧瓶。

您可以尝试通过POSTMAN(Chrome插件)发送请求,而不是cURL。

通过卷曲: Right side window shows the Result

右侧窗口中显示的结果

通过邮差(Chrome的插件):

enter image description here

+0

工作,谢谢。 –

+0

什么是您正在使用的Python版本? –

+1

对不起,前一个工作我只是忘了发送它为json。谢谢 –

相关问题