Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions redis/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,16 +92,16 @@


class Encoder(object):
"Encode strings to bytes and decode bytes to strings"
"Encode strings to bytes-like and decode bytes-like to strings"

def __init__(self, encoding, encoding_errors, decode_responses):
self.encoding = encoding
self.encoding_errors = encoding_errors
self.decode_responses = decode_responses

def encode(self, value):
"Return a bytestring representation of the value"
if isinstance(value, bytes):
"Return a bytestring or bytes-like representation of the value"
if isinstance(value, bytes) or isinstance(value, memoryview):
return value
elif isinstance(value, bool):
# special case bool since it is a subclass of int
Expand All @@ -122,7 +122,7 @@ def encode(self, value):
return value

def decode(self, value, force=False):
"Return a unicode string from the byte representation"
"Return a unicode string from the bytes-like representation"
if (self.decode_responses or force) and isinstance(value, bytes):
value = value.decode(self.encoding, self.encoding_errors)
return value
Expand Down Expand Up @@ -738,6 +738,12 @@ def read_response(self):
raise response
return response

def _maybe_to_bytes(self, arg):
if isinstance(arg, memoryview):
return arg.tobytes()
else:
return arg

def pack_command(self, *args):
"Pack a series of arguments into the Redis protocol"
output = []
Expand Down Expand Up @@ -767,7 +773,7 @@ def pack_command(self, *args):
else:
buff = SYM_EMPTY.join(
(buff, SYM_DOLLAR, str(arg_length).encode(),
SYM_CRLF, arg, SYM_CRLF))
SYM_CRLF, self._maybe_to_bytes(arg), SYM_CRLF))
output.append(buff)
return output

Expand Down
13 changes: 13 additions & 0 deletions tests/test_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -2399,6 +2399,19 @@ def test_xread(self, r):
# xread starting at the last message returns an empty list
assert r.xread(streams={stream: m2}) == []

# memoryviews
m3 = r.xadd(stream, {'boom': memoryview(b'bop')})
expected = [
[
stream.encode(),
[
get_stream_message(r, stream, m3),
]
]
]

assert r.xread(streams={stream: m2}) == expected

@skip_if_server_version_lt('5.0.0')
def test_xreadgroup(self, r):
stream = 'stream'
Expand Down