gpt4 book ai didi

python - sqlalchemy.exc.DataError : (psycopg2. DataError) 类型字符变化的值太长

转载 作者:行者123 更新时间:2023-11-29 12:17:32 25 4
gpt4 key购买 nike

我尝试使用 SQL Alchemy 在 postgresql 数据库中保存哈希密码。表脚本是:

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")

关于python - sqlalchemy.exc.DataError : (psycopg2. DataError) 类型字符变化的值太长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44716412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com