Initialize the connection, authenticate and select a database
(self, check_health: bool = True)
| 1092 | self.on_connect_check_health(check_health=True) |
| 1093 | |
| 1094 | def on_connect_check_health(self, check_health: bool = True): |
| 1095 | "Initialize the connection, authenticate and select a database" |
| 1096 | self._parser.on_connect(self) |
| 1097 | parser = self._parser |
| 1098 | |
| 1099 | auth_args = None |
| 1100 | # if credential provider or username and/or password are set, authenticate |
| 1101 | if self.credential_provider or (self.username or self.password): |
| 1102 | cred_provider = ( |
| 1103 | self.credential_provider |
| 1104 | or UsernamePasswordCredentialProvider(self.username, self.password) |
| 1105 | ) |
| 1106 | auth_args = cred_provider.get_credentials() |
| 1107 | |
| 1108 | # if resp version is specified and we have auth args, |
| 1109 | # we need to send them via HELLO |
| 1110 | if auth_args and self.protocol not in [2, "2"]: |
| 1111 | if isinstance(self._parser, _RESP2Parser): |
| 1112 | self.set_parser(_RESP3Parser) |
| 1113 | # update cluster exception classes |
| 1114 | self._parser.EXCEPTION_CLASSES = parser.EXCEPTION_CLASSES |
| 1115 | self._parser.on_connect(self) |
| 1116 | if len(auth_args) == 1: |
| 1117 | auth_args = ["default", auth_args[0]] |
| 1118 | # avoid checking health here -- PING will fail if we try |
| 1119 | # to check the health prior to the AUTH |
| 1120 | self.send_command( |
| 1121 | "HELLO", self.protocol, "AUTH", *auth_args, check_health=False |
| 1122 | ) |
| 1123 | self.handshake_metadata = self.read_response() |
| 1124 | # if response.get(b"proto") != self.protocol and response.get( |
| 1125 | # "proto" |
| 1126 | # ) != self.protocol: |
| 1127 | # raise ConnectionError("Invalid RESP version") |
| 1128 | elif auth_args: |
| 1129 | # avoid checking health here -- PING will fail if we try |
| 1130 | # to check the health prior to the AUTH |
| 1131 | self.send_command("AUTH", *auth_args, check_health=False) |
| 1132 | |
| 1133 | try: |
| 1134 | auth_response = self.read_response() |
| 1135 | except AuthenticationWrongNumberOfArgsError: |
| 1136 | # a username and password were specified but the Redis |
| 1137 | # server seems to be < 6.0.0 which expects a single password |
| 1138 | # arg. retry auth with just the password. |
| 1139 | # https://github.com/andymccurdy/redis-py/issues/1274 |
| 1140 | self.send_command("AUTH", auth_args[-1], check_health=False) |
| 1141 | auth_response = self.read_response() |
| 1142 | |
| 1143 | if str_if_bytes(auth_response) != "OK": |
| 1144 | raise AuthenticationError("Invalid Username or Password") |
| 1145 | |
| 1146 | # if resp version is specified, switch to it |
| 1147 | elif self.protocol not in [2, "2"]: |
| 1148 | if isinstance(self._parser, _RESP2Parser): |
| 1149 | self.set_parser(_RESP3Parser) |
| 1150 | # update cluster exception classes |
| 1151 | self._parser.EXCEPTION_CLASSES = parser.EXCEPTION_CLASSES |