首页 > 解决方案 > 如何将 Flask 路由中的 PATCH 方法作为 API 处理?

问题描述

我有这条路线:

@bp.route('coordinates/<int:id>/update', methods=['PATCH'])
def update_coordinates(id):
    schema = CoordinatesSchema()
    coords = Coordinates.query.get_or_404(id)
    new_data = request                           #????

    # some another logic
    return jsonify({"result": "GOOD"}), 200

我在正文中传递要更新的数据,例如字典:{ "title": "newtitle"}但我如何才能在路线中获取此信息?

标签: pythonapiflask

解决方案


使用 PATCH 请求,您检索请求数据的方式与对其他所有请求类型(例如 POST)的方式相同。根据您发送数据的方式,有几种方法可以检索它:

发送为application/json

data = request.json

发送为application/x-www-form-urlencoded(表单数据)

data = request.form

Content-Type作为没有标题的原始正文发送:

data = request.data

最后一个会给你一个字节字符串,然后你必须相应地处理它。对于您的用例,我建议使用第一个示例并Content-Type: application/json在发送 PATCH 请求时添加标头。


推荐阅读