itsdangerous序列化器报错:int与bytes类型无法拼接
问题分析与解决:itsdangerous TypeError: unsupported operand type(s) for +: 'int' and 'bytes'
问题重现
代码示例
from itsdangerous import URLSafeTimedSerializer as Serialiser class User(db.Model, UserMixin): def get_reset_token(self, expiration_sec=1800): s = Serialiser(app.config['SECRET_KEY'], expiration_sec) return s.dumps({'user_id': self.id})
错误栈
rv = self.make_signer(salt).sign(payload) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\itsdangerous\timed.py", line 55, in sign return value + sep + self.get_signature(value) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\itsdangerous\signer.py", line 209, in get_signature key = self.derive_key() ^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\itsdangerous\signer.py", line 195, in derive_key bytes, self.digest_method(bytes(self.salt) + b"signer" + secret_key).digest() ^^^^^^^^^^^^^^^^^^^^^ TypeError: unsupported operand type(s) for +: 'int' and 'bytes'
问题原因
- 参数传递错误:
URLSafeTimedSerializer的第二个参数是salt(要求字符串类型),你把整数类型的expiration_sec传给了这个参数,后续代码尝试将整数salt与字节串b"signer"拼接时触发类型不匹配错误。 - 潜在配置问题:如果
app.config['SECRET_KEY']被设置为整数而非字符串,也会引发同类错误。
解决方案
1. 修正序列化器参数传递
有两种正确设置过期时间的方式:
方式一:构造序列化器时用关键字参数指定expires_in
from itsdangerous import URLSafeTimedSerializer as Serialiser class User(db.Model, UserMixin): def get_reset_token(self, expiration_sec=1800): s = Serialiser(app.config['SECRET_KEY'], expires_in=expiration_sec) return s.dumps({'user_id': self.id})
方式二:在dumps方法中指定expires_in
from itsdangerous import URLSafeTimedSerializer as Serialiser class User(db.Model, UserMixin): def get_reset_token(self, expiration_sec=1800): s = Serialiser(app.config['SECRET_KEY']) return s.dumps({'user_id': self.id}, expires_in=expiration_sec)
2. 确保SECRET_KEY为字符串类型
检查Flask配置,将SECRET_KEY设置为字符串格式,例如:
app.config['SECRET_KEY'] = 'your-strong-random-secret-key-here'
禁止使用整数或其他非字符串类型作为密钥。
内容的提问来源于stack exchange,提问作者Michael
相关产品推荐
相关产品推荐

