简体   繁体   中英

How to perform POST action on resources using Flask

i am learning python and the REST API with Flask. In one of the tutorials the below mentioned method is used to do POST operation to the resources.

@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
        

at runtime when i access the following link

http://127.0.0.1:5000/todo/api/v1.0/createTask

i receive the following error:

Method Not Allowed
The method is not allowed for the requested URL.

please let me know how to fix this error

code :

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)

update :

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?

you need to count also for the [GET] method, because what your actually trying to do is get not POST

add `

methods = ["GET", "POST"]
if request.method == "post":
   your code here
else:
   return render_template("createtasks")

`you need to specify the get method for the createTask, i dont know how you did it because its not mentioned in your code but i assumed its a template.

When you send out the request, did you do it in the browser? I think it will send as a GET request by default for http://127.0.0.1:5000/todo/api/v1.0/createTask .

If you really want to send a POST request, you can do it via your terminal (curl) or maybe try to use postman.

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

Or if you think the GET method should also be accepted for this endpoint, then you can update your code (Not really recommended, because it is against the initial definition difference between POST and 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM