helpers.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. import copy
  2. import random
  3. import string
  4. from typing import List, Tuple
  5. import redis
  6. from redis.typing import KeysT, KeyT
  7. def list_or_args(keys: KeysT, args: Tuple[KeyT, ...]) -> List[KeyT]:
  8. # returns a single new list combining keys and args
  9. try:
  10. iter(keys)
  11. # a string or bytes instance can be iterated, but indicates
  12. # keys wasn't passed as a list
  13. if isinstance(keys, (bytes, str)):
  14. keys = [keys]
  15. else:
  16. keys = list(keys)
  17. except TypeError:
  18. keys = [keys]
  19. if args:
  20. keys.extend(args)
  21. return keys
  22. def nativestr(x):
  23. """Return the decoded binary string, or a string, depending on type."""
  24. r = x.decode("utf-8", "replace") if isinstance(x, bytes) else x
  25. if r == "null":
  26. return
  27. return r
  28. def delist(x):
  29. """Given a list of binaries, return the stringified version."""
  30. if x is None:
  31. return x
  32. return [nativestr(obj) for obj in x]
  33. def parse_to_list(response):
  34. """Optimistically parse the response to a list."""
  35. res = []
  36. special_values = {"infinity", "nan", "-infinity"}
  37. if response is None:
  38. return res
  39. for item in response:
  40. if item is None:
  41. res.append(None)
  42. continue
  43. try:
  44. item_str = nativestr(item)
  45. except TypeError:
  46. res.append(None)
  47. continue
  48. if isinstance(item_str, str) and item_str.lower() in special_values:
  49. res.append(item_str) # Keep as string
  50. else:
  51. try:
  52. res.append(int(item))
  53. except ValueError:
  54. try:
  55. res.append(float(item))
  56. except ValueError:
  57. res.append(item_str)
  58. return res
  59. def parse_list_to_dict(response):
  60. res = {}
  61. for i in range(0, len(response), 2):
  62. if isinstance(response[i], list):
  63. res["Child iterators"].append(parse_list_to_dict(response[i]))
  64. try:
  65. if isinstance(response[i + 1], list):
  66. res["Child iterators"].append(parse_list_to_dict(response[i + 1]))
  67. except IndexError:
  68. pass
  69. elif isinstance(response[i + 1], list):
  70. res["Child iterators"] = [parse_list_to_dict(response[i + 1])]
  71. else:
  72. try:
  73. res[response[i]] = float(response[i + 1])
  74. except (TypeError, ValueError):
  75. res[response[i]] = response[i + 1]
  76. return res
  77. def random_string(length=10):
  78. """
  79. Returns a random N character long string.
  80. """
  81. return "".join( # nosec
  82. random.choice(string.ascii_lowercase) for x in range(length)
  83. )
  84. def decode_dict_keys(obj):
  85. """Decode the keys of the given dictionary with utf-8."""
  86. newobj = copy.copy(obj)
  87. for k in obj.keys():
  88. if isinstance(k, bytes):
  89. newobj[k.decode("utf-8")] = newobj[k]
  90. newobj.pop(k)
  91. return newobj
  92. def get_protocol_version(client):
  93. if isinstance(client, redis.Redis) or isinstance(client, redis.asyncio.Redis):
  94. return client.connection_pool.connection_kwargs.get("protocol")
  95. elif isinstance(client, redis.cluster.AbstractRedisCluster):
  96. return client.nodes_manager.connection_kwargs.get("protocol")