Redis集群认证失败:无法创建客户端,触发int()转换无效错误
Redis集群连接失败(含特殊字符密码)解决方案
问题背景
无法通过用户名/密码连接Redis集群,创建客户端失败。使用的代码如下:
from redis.cluster import RedisCluster, ClusterNode def get_redis_connection(): url = f"rediss://{uname}:{passwd}@{host}:{port}/0" connection = RedisCluster.from_url(url) if connection.ping(): print("Success") else: print("Failed")
运行后报错:Error occurred in get_redis_connection: invalid literal for int() with base 10:
注意:密码包含字母、数字及特殊字符(含单引号),示例连接URL:rediss://travel-tire:v'Y:[4o2n:3*s@hostname:port,环境已通过pip install redis安装依赖。
报错原因
密码中的特殊字符(比如单引号'、冒号:)未做URL编码,直接拼接进URL后会破坏URL的结构解析逻辑。Redis客户端解析URL时,会错误地把密码里的冒号识别为数据库编号的分隔符,导致把非数字内容当作数据库ID尝试转换为整数,触发上述报错。
解决方案
对用户名和密码进行URL编码,使用Python标准库urllib.parse.quote()转义特殊字符,确保URL结构符合规范。
修改后的代码:
from redis.cluster import RedisCluster from urllib.parse import quote def get_redis_connection(): # 对用户名和密码做URL编码,转义特殊字符 encoded_uname = quote(uname) encoded_passwd = quote(passwd) # 拼接编码后的URL url = f"rediss://{encoded_uname}:{encoded_passwd}@{host}:{port}/0" connection = RedisCluster.from_url(url) if connection.ping(): print("Success") else: print("Failed")
说明
quote()函数会自动转义URL中的特殊字符(如'、:、*等),将其转换为符合URL规范的编码形式(比如'转为%27,:转为%3A)- 编码后的URL能被Redis客户端正确解析,不会出现分隔符混淆的问题
内容的提问来源于stack exchange,提问作者Raman
相关产品推荐
相关产品推荐

