我正在用 Flask 学习 python 和 REST API。在其中一个教程中,下面提到的方法用于对资源进行 POST 操作。
@app.route('/todo/api/v1.0/createTask', 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
在运行时访问以下链接
http://127.0.0.1:5000/todo/api/v1.0/createTask
我收到以下错误:
Method Not Allowed
The method is not allowed for the requested URL.
请让我知道如何解决此错误
代码:
from flask import Flask, jsonify
from flask import abort
from flask import make_response
from flask import 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({'error': 'Not found'}), 404)
@app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
return jsonify({'tasks': tasks})
@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id):
'''
more appropriate for error handlering
'''
task = [task for task in tasks if task['id'] == task_id]
if len(task) == 0:
return not_found("")
return jsonify({'task': task[0]})
@app.route('/todo/api/v1.0/createTask', 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
if __name__ == '__main__':
app.run(debug=True)
更新:
i would like to know the purpose of
if not request.json or not 'title' in request.json:
abort(400)
what does
if not request.json or not 'title' in request.json:
mean?
当您发出请求时,您是在浏览器中进行的吗?我认为默认情况下它将作为 GET 请求发送给http://127.0.0.1:5000/todo/api/v1.0/createTask
.
如果你真的想发送一个 POST 请求,你可以通过你的终端(curl)或者尝试使用邮递员。
curl -X POST http://127.0.0.1:5000/todo/api/v1.0/createTask
curl -X POST -d '{"title": "AAA", "description": "AAADESCRIPTION"}' -H 'Content-Type: application/json' http://127.0.0.1:5000/todo/api/v1.0/createTask
或者,如果您认为该端点也应该接受 GET 方法,那么您可以更新您的代码(不真正推荐,因为它违反了 POST 和 GET 之间的初始定义差异)。
# @app.route('/todo/api/v1.0/createTask', methods=['POST', 'GET'])
@app.route('/todo/api/v1.0/createTask', methods=['POST'])
def create_task():
request_params = request.get_json()
if not request_params or 'title' not in request_params:
abort(400)
task = {
'id': tasks[-1]['id'] + 1,
'title': request_params['title'],
'description': request_params.get('description', ""),
'done': False
}
tasks.append(task)
return jsonify({'task': task}), 201
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句