【问题标题】:How to perform POST action on resources using Flask如何使用 Flask 对资源执行 POST 操作
【发布时间】:2021-02-26 10:19:41
【问题描述】:

我正在使用 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?

【问题讨论】:

    标签: python python-3.x flask


    【解决方案1】:

    当您发出请求时,您是在浏览器中进行的吗?我认为默认情况下它将作为 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
    

    【讨论】:

    • thanx 但是只要我只想做 POST,指定 GET 和 POST 的目的是什么?你能告诉我这个 if 语句的含义或目的吗:如果不是 request.json或在 request.json 中不是“标题”:ii 无法理解
    • 我想这就是你想要做的:request_params = request.get_json() if not request_params or 'tite' not in request_params:
    • thanx 你能告诉我 :request_params = request.get_json() 的含义吗?它实际上是做什么的
    • request.get_json() 将 JSON 对象(作为 POST 请求中的参数传递)转换为 Python 数据。你可以检查一下:digitalocean.com/community/tutorials/…
    【解决方案2】:

    您还需要计算 [GET] 方法,因为您实际尝试做的不是 POST

    添加 `

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

    `你需要为createTask指定get方法,我不知道你是怎么做到的,因为你的代码中没有提到它,但我假设它是一个模板。

    【讨论】:

    • thanx 但是只要我只想做 POST,指定 GET 和 POST 的目的是什么?你能告诉我这个 if 语句的含义或目的吗:如果不是 request.json或在 request.json 中不是“标题”:ii 无法理解
    • 当您在浏览器中打开 127.0.0.1:5000/todo/api/v1.0/createTask 时,它是一个 get 方法,当您发送您在字段中输入的信息时,它是一个 post 方法
    猜你喜欢
    • 1970-01-01
    • 2014-06-25
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    • 1970-01-01
    • 2015-01-26
    相关资源
    最近更新 更多