You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 05:05:36