最近在使用 Python 的 itsdangerous 发送激活邮件,需要使用到 token,生成 token 的代码如下:
def generate_confirmation_token(self, expiration=3600):
s = Serializer(current_app.config['SECRET_KEY'], expiration)
return s.dumps({'confirm': self.id}).decode('utf-8')
结果出现如下错误:
TypeError: unsupported operand type(s) for +: 'int' and 'bytes'
出现问题原因
应该是版本升级导致,修改代码写法。
解决方案
目前使用的 itsdangerous 版本是:2.1.2。
写法如下:
def generate_confirmation(self):
s = TimedSerializer(current_app.secret_key, 'confirmation')
return s.dumps(self.id)
def check_confirmation(self, token, max_age=3600):
s = TimedSerializer(current_app.secret_key, 'confirmation')
return s.loads(token, max_age=max_age) == self.id
这样就解决了这个问题。