在 SQLAlchemy 中提交时出现 MySQLInterfaceError

MySQLInterfaceError when commiting in SQLAlchemy

我正在使用 Flask 和 SQLAlchemy 构建一个网络 API,以将数据推送到 MySQL 数据库。每当我将对象 'Project' 添加到会话并提交它时,我都会收到以下错误:

result[key] = self._cmysql.convert_to_mysql(value)[0] _mysql_connector.MySQLInterfaceError: Python type tuple cannot be converted

我要提交的 class:

class Project(Base):
__tablename__ = 'project'

id = Column(Integer, primary_key=True, autoincrement=True)
title = Column(String(255), unique=True, nullable=False)
client = Column(String(255), unique=False, nullable=False)
work_week = Column(Integer, unique=False, nullable=False)
start_date = Column(Date, unique=False, nullable=False)
end_date = Column(Date, unique=False, nullable=True)
description = Column(String(255), unique=False, nullable=True)

def __init__(self, title, client, work_week, start_date, end_date, description):
    self.title = title
    self.client = client
    self.work_week = work_week
    self.start_date = start_date,
    self.end_date = end_date,
    self.description = description

用于(反)序列化上述内容的 MarshMallow 模式 class:

class ProjectSchema(Schema):
   id = fields.Integer()
   title = fields.Str()
   client = fields.Str()
   work_week = fields.Integer()
   start_date = fields.Date()
   end_date = fields.Date()
   description = fields.Str()

最后是在运行时生成错误值的方法:

def post_project(project: str): '{"title":"Project X","client":"Klant X","work_week":40,"start_date":"2021-11-08","end_date":"2021-11-15","description":"Dit is een voorbeeld."}'
schema = ProjectSchema() schema: <ProjectSchema(many=False)>
project_data = schema.loads(project) {'end_date': datetime.date(2021, 11, 15), 'start_date': datetime.date(2021, 11, 8), 'description': 'Dit is een voorbeeld.', 'title': 'Project X', 'client': 'Klant X', 'work_week': 40}
result = Project(**project_data) <api.models.project.Project object at 0x0000023271C0B640>

session.add(result)
session.commit() <-- ERROR

return '', 200

我很困惑为什么它会抱怨无法转换的元组。任何人都可以阐明这个问题吗?

谢谢。

在你的Project.__init__中,你有

    ...
    self.start_date = start_date,
    self.end_date = end_date,
    ...

注意行尾的逗号,它将这些值转换为元组。

是否有必要像这样重新实现 __init__Base 中的那个应该已经将 kwargs 分配给各个成员,所以也许您可以通过完全删除该方法来最好地解决您的问题...