sqlalchemy.exc.DataError: (psycopg2.DataError) value too long for type character varying

sqlalchemy.exc.DataError: (psycopg2.DataError) value too long for type character varying

我尝试使用 SQL Alchemy 在 postgresql 数据库中保存散列密码。 table 脚本是:

Create Table "User"(
Id serial Primary key,
UserName varchar(50) unique not null,
Nikname varchar(50) not null,
"password" varchar(172) not null,
FirstName varchar(75) not null,
LastName varchar(75) not null,
BirthDate date not null,
CreateDate date not null,
Status smallint Not null
)

这是映射:

user = Table('User', metadata,
         Column('id', Sequence(name='User_id_seq'), primary_key=True),
         Column('username', String(50), unique=True, nullable=False),
         Column('nikname', String(50), nullable=False),
         Column('firstname', String(75), nullable=False),
         Column('lastname', String(75), nullable=False),
         Column('password', String(172), nullable=False),
         Column('status', Integer, nullable=False),
         Column('birthdate', Date, nullable=False),
         Column('createdate', Date, nullable=False)
    )

当我尝试插入数据时,引发了这个异常:

sqlalchemy.exc.DataError: (psycopg2.DataError) value too long for type character varying(172)
[SQL: 'INSERT INTO "User" (id, username, nikname, firstname, lastname, password, status, birthdate, createdate) VALUES (nextval(\'"User_id_seq"\'), %(username)s, %(nikname)s, %(firstname)s, %(lastname)s, %(password)s, %(status)s, %(birthdate)s, %(createdate)s) RETURNING "User".id'] [parameters: {'username': 'hoseinyeganloo@gmail.com', 'nikname': 'Laughing Death', 'firstname': 'Hosein', 'lastname': 'Yegnloo', 'password': b'i1SlFeDkCZ0BJYanhINGCZC80rqVYABHAS/Ot2AWDgzPZCtshMNRZGHeosx3PvLqsCWzZfPZpsT+UZZLShmQxfbO5VJ4xJbLNjbb0n8HuazQy+0u5Ws2DCtmdDh+HFBTKCAiNuzUGueurP9d2VE3tHwHpX+hCMS1RB4KIOUORKw=', 'status': 1, 'birthdate': datetime.datetime(1990, 3, 1, 0, 0), 'createdate': datetime.datetime(2017, 6, 23, 0, 0)}]

但是如您所见,数据也非常适合字段,并且当我在 pgadmin 中执行此查询时没有错误! 我认为问题出在我的映射中。我将字符串更改为文本但错误抵抗:|

有什么想法吗?

不知道有没有帮助。当所有字符都是数字时,代码工作没有错误。

我尝试插入一些数字而不是散列密码,它成功了!

更新

我发现是字符编码的问题!一些如何 SQLAlchemy 增加传递字符串的大小!现在我正在努力阻止它!

问题不在于映射或字符集或 sql Alchemy 中的任何类似内容! 这是我的密码!当我尝试将哈希结果转换为 base64 字符串时,结果将是 BinaryString!不是字符串。

'password': b'i1SlFeDkCZ0BJYanhING....

因此,为了解决这个问题,我需要将 base64 结果解码为 un​​icode 字符串,然后再将其保存到数据库!

u.password = u.password.decode("utf-8", "ignore")

这个问题的出现是因为 postgresql 和其他 ORM 数据结构定义是严格类型的,不像 SQL 那样松散。我已经确定了两方面的问题

  1. db.Column定义
  2. 按方法发布数据应遵循模型方法参数顺序

以上内容可能不会影响 SQL迁移到其他 ORM 的 Alchemy 数据库交互需要您遵守以上内容。

  1. Table定义

    __tablename__ = 'test'
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    accountNumber = db.Column(db.String(255))
    description = db.Column(db.String(255), nullable=False)
    accountType = db.Column(db.String(255), nullable=False)
    
  2. 按列角色顺序发布数据

    createAccount(accountNumber, description, accountType)