使用JWT时遇AttributeError: 'str'对象无decode属性问题求助
解决
AttributeError: 'str' object has no attribute 'decode'问题 这个错误基本是Python版本差异导致的——Python 3里字符串(str)本身就是Unicode编码,不需要再调用decode()方法,只有字节流(bytes)类型才有这个方法。结合JWT登录场景,常见触发场景和修复方式如下:
场景1:JWT验证时错误解码token
如果用PyJWT库时,对已经是字符串的token调用了decode(),比如:
# 错误示例:str类型token调用decode报错 token = request.headers.get('Authorization').split(' ')[1] decoded_token = token.decode('utf-8') payload = jwt.decode(decoded_token, secret_key, algorithms=['HS256'])
修复:直接将字符串token传入jwt.decode(),无需额外解码:
token = request.headers.get('Authorization').split(' ')[1] payload = jwt.decode(token, secret_key, algorithms=['HS256'])
场景2:生成JWT时处理结果错误
PyJWT 2.x版本中,jwt.encode()默认返回字符串,若旧代码仍对其调用decode()会报错:
# 错误示例:PyJWT 2.x中encode返回str,调用decode报错 token = jwt.encode(payload, secret_key, algorithm='HS256').decode('utf-8')
修复:直接使用jwt.encode()的返回值即可:
token = jwt.encode(payload, secret_key, algorithm='HS256')
若需兼容旧版本字节流需求,可指定encoding=None让encode()返回bytes后再解码:
token_bytes = jwt.encode(payload, secret_key, algorithm='HS256', encoding=None) token_str = token_bytes.decode('utf-8')
场景3:数据库取出token时误操作
从数据库取出的token已是字符串,若再次调用decode()也会触发错误,直接使用取出的字符串即可。
如果以上方案未解决问题,贴出你的登录接口代码和导入代码,可进一步定位问题。
内容的提问来源于stack exchange,提问作者Wade
相关产品推荐
相关产品推荐

