python - 如何将 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"}
但我如何才能在路线中获取此信息?
解决方案
使用 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 请求时添加标头。
推荐阅读
- animation - THREE.js 中的动画填充模式“向前”
- python - 我无法让我的代码执行用户输入选择的函数
- python - RTU Modbus Slave 的 Python 脚本
- pyspark - 尝试从 PyCharm 运行 PySpark 应用程序时出现 SocketTimeoutException
- paypal - 具有多个定期订阅的贝宝只接受第一个
- javascript - 提取 Json 数据并使用 Protractor 验证值
- powerbi - SSAS 表格模型和 Power BI - 报表中的周筛选
- sql - 如何在报表生成器中合并行组?
- java - 如果需要更改库功能我该怎么办
- python - 尝试同时执行多个请求,然后使用 Aiohttp 和 python 添加到集合中