sqlalchemy.exc.DataError:(psycopg2.DataError)值对于类型字符变化来说太长

Hos*_*loo 5 python postgresql sqlalchemy psycopg2

我尝试使用 SQL Alchemy 在 PostgreSQL 数据库中保存哈希密码。创建表脚本如下:

Create Table "User"(
Id serial Primary key,
UserName varchar(50) unique not null,
Nickname 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
)
Run Code Online (Sandbox Code Playgroud)

这是映射:

user = Table('User', metadata,
         Column('id', Sequence(name='User_id_seq'), primary_key=True),
         Column('username', String(50), unique=True, nullable=False),
         Column('nickname', 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)
    )
Run Code Online (Sandbox Code Playgroud)

当我尝试插入数据时,出现此异常:

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)}]
Run Code Online (Sandbox Code Playgroud)

但正如您所看到的,数据完全符合字段,并且当我在 pgadmin 内执行此查询时没有错误!我认为问题出在我的映射上。我更改StringText但错误仍然存​​在。

有任何想法吗?

我不知道它是否有帮助,但是当所有字符都是数字时,代码可以正常工作。

我尝试插入一些数字而不是哈希密码,这有效!

更新

我发现是字符编码的问题!不知何故,SQLAlchemy 增加了传递字符串的允许大小!现在我正在努力阻止它!

Hos*_*loo 4

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

“密码”:b'i1SlFeDkCZ0BJYanhING ....

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

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