Skip to content

Commit 9f3791f

Browse files
authored
Fix KeyError in async cluster - initialize before execute multi key commands (#2439)
* Fix KeyError in async cluster * link to issue * typo
1 parent 5179776 commit 9f3791f

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

redis/commands/cluster.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,25 @@ async def _split_command_across_slots(self, command: str, *keys: KeyT) -> int:
316316
# Sum up the reply from each command
317317
return sum(await self._execute_pipeline_by_slot(command, slots_to_keys))
318318

319+
async def _execute_pipeline_by_slot(
320+
self, command: str, slots_to_args: Mapping[int, Iterable[EncodableT]]
321+
) -> List[Any]:
322+
if self._initialize:
323+
await self.initialize()
324+
read_from_replicas = self.read_from_replicas and command in READ_COMMANDS
325+
pipe = self.pipeline()
326+
[
327+
pipe.execute_command(
328+
command,
329+
*slot_args,
330+
target_nodes=[
331+
self.nodes_manager.get_node_from_slot(slot, read_from_replicas)
332+
],
333+
)
334+
for slot, slot_args in slots_to_args.items()
335+
]
336+
return await pipe.execute()
337+
319338

320339
class ClusterManagementCommands(ManagementCommands):
321340
"""

tests/test_asyncio/test_cluster.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -802,6 +802,15 @@ async def test_unlink(self, r: RedisCluster) -> None:
802802
await asyncio.sleep(0.1)
803803
assert await r.unlink(*d.keys()) == 0
804804

805+
async def test_initialize_before_execute_multi_key_command(
806+
self, request: FixtureRequest
807+
) -> None:
808+
# Test for issue https://github.com/redis/redis-py/issues/2437
809+
url = request.config.getoption("--redis-url")
810+
r = RedisCluster.from_url(url)
811+
assert 0 == await r.exists("a", "b", "c")
812+
await r.close()
813+
805814
@skip_if_redis_enterprise()
806815
async def test_cluster_myid(self, r: RedisCluster) -> None:
807816
node = r.get_random_node()

0 commit comments

Comments
 (0)