2016-11-04 2 views
0

자습서 here을 수행 중이며 처음 create_task 기능을 설정하기 시작합니다. 나는 창에 오류POST 요청을 시도 할 때 Flask에 REST API를 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 명령을

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을 성공적으로 수행 할 수있었습니다. 나는 컬 명령도 복사했다. – idjaw

답변

0

코드가 정상적으로 작동합니다. 플라스크를 다시 설치하십시오.

cURL 대신 POSTMAN (Chrome Plugin)을 통해 요청을 전송할 수도 있습니다. cURL을 통해

: Right side window shows the Result

우측 창은 결과를 우편 배달부 (크롬 플러그인)을 통해

를 보여준다는 :

enter image description here

+0

그 덕분에, 고마워. –

+0

사용중인 파이썬 버전은 무엇입니까? –

+1

죄송합니다, 그 이전의 일은 방금 json으로 보내는 것을 잊었습니다. 고맙습니다 –

관련 문제