You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask API POST方法无法接收数据,数据库插入失败

Flask POST请求SQLAlchemy OperationalError问题排查与解决

问题描述

开发Flask应用时,已实现REST API,新增视图层后POST请求出现报错:SQLAlchemy抛出OperationalError,提示'waiter'列不能为null,SQL执行语句为INSERT INTO orders (waiter, table) VALUES (%s, %s),参数为(None, None)。调试发现API的POST方法中**kwargs为空字典。

原因分析

  • API的POST方法通过@use_kwargs(PostOrderSchema, location='json')指定从JSON格式解析请求参数,但视图层使用requests.post的data参数发送的是表单格式数据,而非JSON,导致API无法解析到参数,最终kwargs为空。
  • 视图层中table参数传的是字符串'3',而PostOrderSchema定义table为fields.Integer(),即使参数被接收,也会因类型不匹配被过滤,进一步导致参数缺失。

解决方案

  1. 视图层改用JSON格式发送请求:将requests.post的data参数替换为json参数,确保请求体为JSON格式。
  2. 参数类型匹配:确保发送的参数类型与PostOrderSchema定义一致(如table用整数而非字符串)。
  3. 可选:兼容表单格式(不推荐REST API):若需支持表单提交,可修改API的@use_kwargs装饰器的location参数为'form',但REST API标准推荐使用JSON格式。

代码修正示例

视图层POST方法修正

def post(self):
    form = AddEditOrderForm()

    if form.validate_on_submit():
        # 使用json参数发送JSON格式数据,table改为整数类型
        requests.post(BASE + 'json_orders', json={
            'waiter': 1,  # 实际使用时替换为form.waiter.data.split()[0],注意转成整数
            'orders_date': "2023-01-02",  # 实际使用时替换为form.orders_date.data
            'table': 3  # 改为整数,匹配Schema的Integer类型
        })

    return redirect(url_for('get_all_orders'))

API层调试验证(可选)

在API的POST方法中添加打印语句,确认参数是否被正确接收:

@use_kwargs(PostOrderSchema, location='json')
@marshal_with(OrderSchema)
def post(self, **kwargs):
    print("请求JSON数据:", request.get_json())
    print("接收的kwargs:", kwargs)
    order = add_to_db(Order, **kwargs)
    return order

额外检查点

  • 确认Order模型包含waiter、table、orders_date字段,且字段类型与PostOrderSchema定义匹配。
  • 确保add_to_db函数正确将kwargs中的属性赋值给Order对象(当前实现无问题)。

内容的提问来源于stack exchange,提问作者Diana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 17:53:25