Skip to main content
 首页 » 编程设计

python之如何将 Flask 路由中的 PATCH 方法作为 API 处理

2024年12月31日9Free-Thinker

我有这条路线:

@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"} 但我如何在路由中获取此信息?

请您参考如下方法:

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

作为 application/json 发送:

data = request.json 

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

data = request.form 

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

data = request.data 

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