Skip to content
This repository has been archived by the owner on Feb 21, 2023. It is now read-only.

Commit

Permalink
Browse files Browse the repository at this point in the history
hrandfield (redis/redis-py#1513)

Signed-off-by: Andrew-Chen-Wang <acwangpython@gmail.com>
  • Loading branch information
Andrew-Chen-Wang committed Oct 4, 2021
1 parent b7ede71 commit e41b41c
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
22 changes: 22 additions & 0 deletions aioredis/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2041,6 +2041,28 @@ def pttl(self, name: KeyT) -> Awaitable:
"""Returns the number of milliseconds until the key ``name`` will expire"""
return self.execute_command("PTTL", name)

def hrandfield(
self, key: str, count: int = None, withvalues: bool = False
) -> Awaitable:
"""
Return a random field from the hash value stored at key.
count: if the argument is positive, return an array of distinct fields.
If called with a negative count, the behavior changes and the command
is allowed to return the same field multiple times. In this case,
the number of returned fields is the absolute value of the
specified count.
withvalues: The optional WITHVALUES modifier changes the reply so it
includes the respective values of the randomly selected hash fields.
"""
params = []
if count is not None:
params.append(count)
if withvalues:
params.append("WITHVALUES")

return self.execute_command("HRANDFIELD", key, *params)

def randomkey(self) -> Awaitable:
"""Returns the name of a random key"""
return self.execute_command("RANDOMKEY")
Expand Down
13 changes: 13 additions & 0 deletions tests/test_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -962,6 +962,19 @@ async def test_pttl_no_key(self, r: aioredis.Redis):
"""PTTL on servers 2.8 and after return -2 when the key doesn't exist"""
assert await r.pttl("a") == -2

@skip_if_server_version_lt("6.2.0")
def test_hrandfield(self, r):
assert await r.hrandfield("key") is None
await r.hset("key", mapping={"a": 1, "b": 2, "c": 3, "d": 4, "e": 5})
assert await r.hrandfield("key") is not None
assert len(await r.hrandfield("key", 2)) == 2
# with values
assert len(await r.hrandfield("key", 2, True)) == 4
# without duplications
assert len(await r.hrandfield("key", 10)) == 5
# with duplications
assert len(await r.hrandfield("key", -10)) == 10

async def test_randomkey(self, r: aioredis.Redis):
assert await r.randomkey() is None
for key in ("a", "b", "c"):
Expand Down

0 comments on commit e41b41c

Please sign in to comment.