使用Flask-RESTX+SQLAlchemy+MariaDB更新记录遇'tuple'类型错误
Flask-RESTful PUT接口更新Product报错解决方案
问题场景
基于Flask开发的REST API中,Client与Product为一对多关联关系,列表查询、创建、单条查询功能正常,但调用PUT接口更新Product时触发SQLAlchemy类型错误。
触发错误的请求参数:
{ "sku": "tech-gra-001", "description": "Nvidia RTX 3080", "price": 830, "quantity": 5, "client_id": 1 }
错误日志:
sqlalchemy.exc.NotSupportedError: (mariadb.NotSupportedError) Data type 'tuple' in column 0 not supported in MariaDB Connector/Python [SQL: UPDATE product SET sku=?, description=?, price=?, quantity=?, updated_on=? WHERE product.id = ?] [parameters: (('tech-gra-001',), ('Nvidia RTX 3080',), (830,), (5,), datetime.datetime(2023, 5, 20, 17, 52, 22, 718731), 4)]
错误原因
从日志参数可以看到,sku、description等字段的值被包装成了元组(tuple),这是因为在resource.py的PUT方法中,前四个赋值语句末尾多了逗号,导致变量被赋值为元组而非原始的字符串/整数类型,SQLAlchemy无法将元组类型映射到数据库字段类型。
修复代码
修改resource.py中的ProductAPI类的PUT方法,去掉赋值语句末尾的逗号:
@ns.route("/product/<int:id>") class ProductAPI(Resource): @ns.expect(product_input_model) @ns.marshal_with(product_model) def put(self, id): product = Product.query.get(id) if product: # 去掉每行末尾的逗号 product.sku = ns.payload["sku"] product.description = ns.payload["description"] product.price = ns.payload["price"] product.quantity = ns.payload["quantity"] product.client_id = ns.payload["client_id"] db.session.commit() return product else: ns.abort(404, f"product with id {id} not found")
验证说明
修复后重新调用PUT接口,参数会以正确的字符串/整数类型传入SQLAlchemy,数据库更新语句可以正常执行,不会再触发类型不支持的错误。
内容的提问来源于stack exchange,提问作者christianbueno.1
相关产品推荐
相关产品推荐

