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

Chi*_*fir 2 python api flask

我有这条路线:

@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
Run Code Online (Sandbox Code Playgroud)

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

dmi*_*kov 7

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

发送为application/json

data = request.json
Run Code Online (Sandbox Code Playgroud)

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

data = request.form
Run Code Online (Sandbox Code Playgroud)

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

data = request.data
Run Code Online (Sandbox Code Playgroud)

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