图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

869 lines
28 KiB

  1. import datetime
  2. from redis.utils import str_if_bytes
  3. def timestamp_to_datetime(response):
  4. "Converts a unix timestamp to a Python datetime object"
  5. if not response:
  6. return None
  7. try:
  8. response = int(response)
  9. except ValueError:
  10. return None
  11. return datetime.datetime.fromtimestamp(response)
  12. def parse_debug_object(response):
  13. "Parse the results of Redis's DEBUG OBJECT command into a Python dict"
  14. # The 'type' of the object is the first item in the response, but isn't
  15. # prefixed with a name
  16. response = str_if_bytes(response)
  17. response = "type:" + response
  18. response = dict(kv.split(":") for kv in response.split())
  19. # parse some expected int values from the string response
  20. # note: this cmd isn't spec'd so these may not appear in all redis versions
  21. int_fields = ("refcount", "serializedlength", "lru", "lru_seconds_idle")
  22. for field in int_fields:
  23. if field in response:
  24. response[field] = int(response[field])
  25. return response
  26. def parse_info(response):
  27. """Parse the result of Redis's INFO command into a Python dict"""
  28. info = {}
  29. response = str_if_bytes(response)
  30. def get_value(value):
  31. if "," not in value and "=" not in value:
  32. try:
  33. if "." in value:
  34. return float(value)
  35. else:
  36. return int(value)
  37. except ValueError:
  38. return value
  39. elif "=" not in value:
  40. return [get_value(v) for v in value.split(",") if v]
  41. else:
  42. sub_dict = {}
  43. for item in value.split(","):
  44. if not item:
  45. continue
  46. if "=" in item:
  47. k, v = item.rsplit("=", 1)
  48. sub_dict[k] = get_value(v)
  49. else:
  50. sub_dict[item] = True
  51. return sub_dict
  52. for line in response.splitlines():
  53. if line and not line.startswith("#"):
  54. if line.find(":") != -1:
  55. # Split, the info fields keys and values.
  56. # Note that the value may contain ':'. but the 'host:'
  57. # pseudo-command is the only case where the key contains ':'
  58. key, value = line.split(":", 1)
  59. if key == "cmdstat_host":
  60. key, value = line.rsplit(":", 1)
  61. if key == "module":
  62. # Hardcode a list for key 'modules' since there could be
  63. # multiple lines that started with 'module'
  64. info.setdefault("modules", []).append(get_value(value))
  65. else:
  66. info[key] = get_value(value)
  67. else:
  68. # if the line isn't splittable, append it to the "__raw__" key
  69. info.setdefault("__raw__", []).append(line)
  70. return info
  71. def parse_memory_stats(response, **kwargs):
  72. """Parse the results of MEMORY STATS"""
  73. stats = pairs_to_dict(response, decode_keys=True, decode_string_values=True)
  74. for key, value in stats.items():
  75. if key.startswith("db.") and isinstance(value, list):
  76. stats[key] = pairs_to_dict(
  77. value, decode_keys=True, decode_string_values=True
  78. )
  79. return stats
  80. SENTINEL_STATE_TYPES = {
  81. "can-failover-its-master": int,
  82. "config-epoch": int,
  83. "down-after-milliseconds": int,
  84. "failover-timeout": int,
  85. "info-refresh": int,
  86. "last-hello-message": int,
  87. "last-ok-ping-reply": int,
  88. "last-ping-reply": int,
  89. "last-ping-sent": int,
  90. "master-link-down-time": int,
  91. "master-port": int,
  92. "num-other-sentinels": int,
  93. "num-slaves": int,
  94. "o-down-time": int,
  95. "pending-commands": int,
  96. "parallel-syncs": int,
  97. "port": int,
  98. "quorum": int,
  99. "role-reported-time": int,
  100. "s-down-time": int,
  101. "slave-priority": int,
  102. "slave-repl-offset": int,
  103. "voted-leader-epoch": int,
  104. }
  105. def parse_sentinel_state(item):
  106. result = pairs_to_dict_typed(item, SENTINEL_STATE_TYPES)
  107. flags = set(result["flags"].split(","))
  108. for name, flag in (
  109. ("is_master", "master"),
  110. ("is_slave", "slave"),
  111. ("is_sdown", "s_down"),
  112. ("is_odown", "o_down"),
  113. ("is_sentinel", "sentinel"),
  114. ("is_disconnected", "disconnected"),
  115. ("is_master_down", "master_down"),
  116. ):
  117. result[name] = flag in flags
  118. return result
  119. def parse_sentinel_master(response):
  120. return parse_sentinel_state(map(str_if_bytes, response))
  121. def parse_sentinel_state_resp3(response):
  122. result = {}
  123. for key in response:
  124. try:
  125. value = SENTINEL_STATE_TYPES[key](str_if_bytes(response[key]))
  126. result[str_if_bytes(key)] = value
  127. except Exception:
  128. result[str_if_bytes(key)] = response[str_if_bytes(key)]
  129. flags = set(result["flags"].split(","))
  130. result["flags"] = flags
  131. return result
  132. def parse_sentinel_masters(response):
  133. result = {}
  134. for item in response:
  135. state = parse_sentinel_state(map(str_if_bytes, item))
  136. result[state["name"]] = state
  137. return result
  138. def parse_sentinel_masters_resp3(response):
  139. return [parse_sentinel_state(master) for master in response]
  140. def parse_sentinel_slaves_and_sentinels(response):
  141. return [parse_sentinel_state(map(str_if_bytes, item)) for item in response]
  142. def parse_sentinel_slaves_and_sentinels_resp3(response):
  143. return [parse_sentinel_state_resp3(item) for item in response]
  144. def parse_sentinel_get_master(response):
  145. return response and (response[0], int(response[1])) or None
  146. def pairs_to_dict(response, decode_keys=False, decode_string_values=False):
  147. """Create a dict given a list of key/value pairs"""
  148. if response is None:
  149. return {}
  150. if decode_keys or decode_string_values:
  151. # the iter form is faster, but I don't know how to make that work
  152. # with a str_if_bytes() map
  153. keys = response[::2]
  154. if decode_keys:
  155. keys = map(str_if_bytes, keys)
  156. values = response[1::2]
  157. if decode_string_values:
  158. values = map(str_if_bytes, values)
  159. return dict(zip(keys, values))
  160. else:
  161. it = iter(response)
  162. return dict(zip(it, it))
  163. def pairs_to_dict_typed(response, type_info):
  164. it = iter(response)
  165. result = {}
  166. for key, value in zip(it, it):
  167. if key in type_info:
  168. try:
  169. value = type_info[key](value)
  170. except Exception:
  171. # if for some reason the value can't be coerced, just use
  172. # the string value
  173. pass
  174. result[key] = value
  175. return result
  176. def zset_score_pairs(response, **options):
  177. """
  178. If ``withscores`` is specified in the options, return the response as
  179. a list of (value, score) pairs
  180. """
  181. if not response or not options.get("withscores"):
  182. return response
  183. score_cast_func = options.get("score_cast_func", float)
  184. it = iter(response)
  185. return list(zip(it, map(score_cast_func, it)))
  186. def sort_return_tuples(response, **options):
  187. """
  188. If ``groups`` is specified, return the response as a list of
  189. n-element tuples with n being the value found in options['groups']
  190. """
  191. if not response or not options.get("groups"):
  192. return response
  193. n = options["groups"]
  194. return list(zip(*[response[i::n] for i in range(n)]))
  195. def parse_stream_list(response):
  196. if response is None:
  197. return None
  198. data = []
  199. for r in response:
  200. if r is not None:
  201. data.append((r[0], pairs_to_dict(r[1])))
  202. else:
  203. data.append((None, None))
  204. return data
  205. def pairs_to_dict_with_str_keys(response):
  206. return pairs_to_dict(response, decode_keys=True)
  207. def parse_list_of_dicts(response):
  208. return list(map(pairs_to_dict_with_str_keys, response))
  209. def parse_xclaim(response, **options):
  210. if options.get("parse_justid", False):
  211. return response
  212. return parse_stream_list(response)
  213. def parse_xautoclaim(response, **options):
  214. if options.get("parse_justid", False):
  215. return response[1]
  216. response[1] = parse_stream_list(response[1])
  217. return response
  218. def parse_xinfo_stream(response, **options):
  219. if isinstance(response, list):
  220. data = pairs_to_dict(response, decode_keys=True)
  221. else:
  222. data = {str_if_bytes(k): v for k, v in response.items()}
  223. if not options.get("full", False):
  224. first = data.get("first-entry")
  225. if first is not None and first[0] is not None:
  226. data["first-entry"] = (first[0], pairs_to_dict(first[1]))
  227. last = data["last-entry"]
  228. if last is not None and last[0] is not None:
  229. data["last-entry"] = (last[0], pairs_to_dict(last[1]))
  230. else:
  231. data["entries"] = {_id: pairs_to_dict(entry) for _id, entry in data["entries"]}
  232. if len(data["groups"]) > 0 and isinstance(data["groups"][0], list):
  233. data["groups"] = [
  234. pairs_to_dict(group, decode_keys=True) for group in data["groups"]
  235. ]
  236. for g in data["groups"]:
  237. if g["consumers"] and g["consumers"][0] is not None:
  238. g["consumers"] = [
  239. pairs_to_dict(c, decode_keys=True) for c in g["consumers"]
  240. ]
  241. else:
  242. data["groups"] = [
  243. {str_if_bytes(k): v for k, v in group.items()}
  244. for group in data["groups"]
  245. ]
  246. return data
  247. def parse_xread(response):
  248. if response is None:
  249. return []
  250. return [[r[0], parse_stream_list(r[1])] for r in response]
  251. def parse_xread_resp3(response):
  252. if response is None:
  253. return {}
  254. return {key: [parse_stream_list(value)] for key, value in response.items()}
  255. def parse_xpending(response, **options):
  256. if options.get("parse_detail", False):
  257. return parse_xpending_range(response)
  258. consumers = [{"name": n, "pending": int(p)} for n, p in response[3] or []]
  259. return {
  260. "pending": response[0],
  261. "min": response[1],
  262. "max": response[2],
  263. "consumers": consumers,
  264. }
  265. def parse_xpending_range(response):
  266. k = ("message_id", "consumer", "time_since_delivered", "times_delivered")
  267. return [dict(zip(k, r)) for r in response]
  268. def float_or_none(response):
  269. if response is None:
  270. return None
  271. return float(response)
  272. def bool_ok(response, **options):
  273. return str_if_bytes(response) == "OK"
  274. def parse_zadd(response, **options):
  275. if response is None:
  276. return None
  277. if options.get("as_score"):
  278. return float(response)
  279. return int(response)
  280. def parse_client_list(response, **options):
  281. clients = []
  282. for c in str_if_bytes(response).splitlines():
  283. # Values might contain '='
  284. clients.append(dict(pair.split("=", 1) for pair in c.split(" ")))
  285. return clients
  286. def parse_config_get(response, **options):
  287. response = [str_if_bytes(i) if i is not None else None for i in response]
  288. return response and pairs_to_dict(response) or {}
  289. def parse_scan(response, **options):
  290. cursor, r = response
  291. return int(cursor), r
  292. def parse_hscan(response, **options):
  293. cursor, r = response
  294. no_values = options.get("no_values", False)
  295. if no_values:
  296. payload = r or []
  297. else:
  298. payload = r and pairs_to_dict(r) or {}
  299. return int(cursor), payload
  300. def parse_zscan(response, **options):
  301. score_cast_func = options.get("score_cast_func", float)
  302. cursor, r = response
  303. it = iter(r)
  304. return int(cursor), list(zip(it, map(score_cast_func, it)))
  305. def parse_zmscore(response, **options):
  306. # zmscore: list of scores (double precision floating point number) or nil
  307. return [float(score) if score is not None else None for score in response]
  308. def parse_slowlog_get(response, **options):
  309. space = " " if options.get("decode_responses", False) else b" "
  310. def parse_item(item):
  311. result = {"id": item[0], "start_time": int(item[1]), "duration": int(item[2])}
  312. # Redis Enterprise injects another entry at index [3], which has
  313. # the complexity info (i.e. the value N in case the command has
  314. # an O(N) complexity) instead of the command.
  315. if isinstance(item[3], list):
  316. result["command"] = space.join(item[3])
  317. result["client_address"] = item[4]
  318. result["client_name"] = item[5]
  319. else:
  320. result["complexity"] = item[3]
  321. result["command"] = space.join(item[4])
  322. result["client_address"] = item[5]
  323. result["client_name"] = item[6]
  324. return result
  325. return [parse_item(item) for item in response]
  326. def parse_stralgo(response, **options):
  327. """
  328. Parse the response from `STRALGO` command.
  329. Without modifiers the returned value is string.
  330. When LEN is given the command returns the length of the result
  331. (i.e integer).
  332. When IDX is given the command returns a dictionary with the LCS
  333. length and all the ranges in both the strings, start and end
  334. offset for each string, where there are matches.
  335. When WITHMATCHLEN is given, each array representing a match will
  336. also have the length of the match at the beginning of the array.
  337. """
  338. if options.get("len", False):
  339. return int(response)
  340. if options.get("idx", False):
  341. if options.get("withmatchlen", False):
  342. matches = [
  343. [(int(match[-1]))] + list(map(tuple, match[:-1]))
  344. for match in response[1]
  345. ]
  346. else:
  347. matches = [list(map(tuple, match)) for match in response[1]]
  348. return {
  349. str_if_bytes(response[0]): matches,
  350. str_if_bytes(response[2]): int(response[3]),
  351. }
  352. return str_if_bytes(response)
  353. def parse_cluster_info(response, **options):
  354. response = str_if_bytes(response)
  355. return dict(line.split(":") for line in response.splitlines() if line)
  356. def _parse_node_line(line):
  357. line_items = line.split(" ")
  358. node_id, addr, flags, master_id, ping, pong, epoch, connected = line.split(" ")[:8]
  359. addr = addr.split("@")[0]
  360. node_dict = {
  361. "node_id": node_id,
  362. "flags": flags,
  363. "master_id": master_id,
  364. "last_ping_sent": ping,
  365. "last_pong_rcvd": pong,
  366. "epoch": epoch,
  367. "slots": [],
  368. "migrations": [],
  369. "connected": True if connected == "connected" else False,
  370. }
  371. if len(line_items) >= 9:
  372. slots, migrations = _parse_slots(line_items[8:])
  373. node_dict["slots"], node_dict["migrations"] = slots, migrations
  374. return addr, node_dict
  375. def _parse_slots(slot_ranges):
  376. slots, migrations = [], []
  377. for s_range in slot_ranges:
  378. if "->-" in s_range:
  379. slot_id, dst_node_id = s_range[1:-1].split("->-", 1)
  380. migrations.append(
  381. {"slot": slot_id, "node_id": dst_node_id, "state": "migrating"}
  382. )
  383. elif "-<-" in s_range:
  384. slot_id, src_node_id = s_range[1:-1].split("-<-", 1)
  385. migrations.append(
  386. {"slot": slot_id, "node_id": src_node_id, "state": "importing"}
  387. )
  388. else:
  389. s_range = [sl for sl in s_range.split("-")]
  390. slots.append(s_range)
  391. return slots, migrations
  392. def parse_cluster_nodes(response, **options):
  393. """
  394. @see: https://redis.io/commands/cluster-nodes # string / bytes
  395. @see: https://redis.io/commands/cluster-replicas # list of string / bytes
  396. """
  397. if isinstance(response, (str, bytes)):
  398. response = response.splitlines()
  399. return dict(_parse_node_line(str_if_bytes(node)) for node in response)
  400. def parse_geosearch_generic(response, **options):
  401. """
  402. Parse the response of 'GEOSEARCH', GEORADIUS' and 'GEORADIUSBYMEMBER'
  403. commands according to 'withdist', 'withhash' and 'withcoord' labels.
  404. """
  405. try:
  406. if options["store"] or options["store_dist"]:
  407. # `store` and `store_dist` cant be combined
  408. # with other command arguments.
  409. # relevant to 'GEORADIUS' and 'GEORADIUSBYMEMBER'
  410. return response
  411. except KeyError: # it means the command was sent via execute_command
  412. return response
  413. if type(response) != list:
  414. response_list = [response]
  415. else:
  416. response_list = response
  417. if not options["withdist"] and not options["withcoord"] and not options["withhash"]:
  418. # just a bunch of places
  419. return response_list
  420. cast = {
  421. "withdist": float,
  422. "withcoord": lambda ll: (float(ll[0]), float(ll[1])),
  423. "withhash": int,
  424. }
  425. # zip all output results with each casting function to get
  426. # the properly native Python value.
  427. f = [lambda x: x]
  428. f += [cast[o] for o in ["withdist", "withhash", "withcoord"] if options[o]]
  429. return [list(map(lambda fv: fv[0](fv[1]), zip(f, r))) for r in response_list]
  430. def parse_command(response, **options):
  431. commands = {}
  432. for command in response:
  433. cmd_dict = {}
  434. cmd_name = str_if_bytes(command[0])
  435. cmd_dict["name"] = cmd_name
  436. cmd_dict["arity"] = int(command[1])
  437. cmd_dict["flags"] = [str_if_bytes(flag) for flag in command[2]]
  438. cmd_dict["first_key_pos"] = command[3]
  439. cmd_dict["last_key_pos"] = command[4]
  440. cmd_dict["step_count"] = command[5]
  441. if len(command) > 7:
  442. cmd_dict["tips"] = command[7]
  443. cmd_dict["key_specifications"] = command[8]
  444. cmd_dict["subcommands"] = command[9]
  445. commands[cmd_name] = cmd_dict
  446. return commands
  447. def parse_command_resp3(response, **options):
  448. commands = {}
  449. for command in response:
  450. cmd_dict = {}
  451. cmd_name = str_if_bytes(command[0])
  452. cmd_dict["name"] = cmd_name
  453. cmd_dict["arity"] = command[1]
  454. cmd_dict["flags"] = {str_if_bytes(flag) for flag in command[2]}
  455. cmd_dict["first_key_pos"] = command[3]
  456. cmd_dict["last_key_pos"] = command[4]
  457. cmd_dict["step_count"] = command[5]
  458. cmd_dict["acl_categories"] = command[6]
  459. if len(command) > 7:
  460. cmd_dict["tips"] = command[7]
  461. cmd_dict["key_specifications"] = command[8]
  462. cmd_dict["subcommands"] = command[9]
  463. commands[cmd_name] = cmd_dict
  464. return commands
  465. def parse_pubsub_numsub(response, **options):
  466. return list(zip(response[0::2], response[1::2]))
  467. def parse_client_kill(response, **options):
  468. if isinstance(response, int):
  469. return response
  470. return str_if_bytes(response) == "OK"
  471. def parse_acl_getuser(response, **options):
  472. if response is None:
  473. return None
  474. if isinstance(response, list):
  475. data = pairs_to_dict(response, decode_keys=True)
  476. else:
  477. data = {str_if_bytes(key): value for key, value in response.items()}
  478. # convert everything but user-defined data in 'keys' to native strings
  479. data["flags"] = list(map(str_if_bytes, data["flags"]))
  480. data["passwords"] = list(map(str_if_bytes, data["passwords"]))
  481. data["commands"] = str_if_bytes(data["commands"])
  482. if isinstance(data["keys"], str) or isinstance(data["keys"], bytes):
  483. data["keys"] = list(str_if_bytes(data["keys"]).split(" "))
  484. if data["keys"] == [""]:
  485. data["keys"] = []
  486. if "channels" in data:
  487. if isinstance(data["channels"], str) or isinstance(data["channels"], bytes):
  488. data["channels"] = list(str_if_bytes(data["channels"]).split(" "))
  489. if data["channels"] == [""]:
  490. data["channels"] = []
  491. if "selectors" in data:
  492. if data["selectors"] != [] and isinstance(data["selectors"][0], list):
  493. data["selectors"] = [
  494. list(map(str_if_bytes, selector)) for selector in data["selectors"]
  495. ]
  496. elif data["selectors"] != []:
  497. data["selectors"] = [
  498. {str_if_bytes(k): str_if_bytes(v) for k, v in selector.items()}
  499. for selector in data["selectors"]
  500. ]
  501. # split 'commands' into separate 'categories' and 'commands' lists
  502. commands, categories = [], []
  503. for command in data["commands"].split(" "):
  504. categories.append(command) if "@" in command else commands.append(command)
  505. data["commands"] = commands
  506. data["categories"] = categories
  507. data["enabled"] = "on" in data["flags"]
  508. return data
  509. def parse_acl_log(response, **options):
  510. if response is None:
  511. return None
  512. if isinstance(response, list):
  513. data = []
  514. for log in response:
  515. log_data = pairs_to_dict(log, True, True)
  516. client_info = log_data.get("client-info", "")
  517. log_data["client-info"] = parse_client_info(client_info)
  518. # float() is lossy comparing to the "double" in C
  519. log_data["age-seconds"] = float(log_data["age-seconds"])
  520. data.append(log_data)
  521. else:
  522. data = bool_ok(response)
  523. return data
  524. def parse_client_info(value):
  525. """
  526. Parsing client-info in ACL Log in following format.
  527. "key1=value1 key2=value2 key3=value3"
  528. """
  529. client_info = {}
  530. for info in str_if_bytes(value).strip().split():
  531. key, value = info.split("=")
  532. client_info[key] = value
  533. # Those fields are defined as int in networking.c
  534. for int_key in {
  535. "id",
  536. "age",
  537. "idle",
  538. "db",
  539. "sub",
  540. "psub",
  541. "multi",
  542. "qbuf",
  543. "qbuf-free",
  544. "obl",
  545. "argv-mem",
  546. "oll",
  547. "omem",
  548. "tot-mem",
  549. }:
  550. client_info[int_key] = int(client_info[int_key])
  551. return client_info
  552. def parse_set_result(response, **options):
  553. """
  554. Handle SET result since GET argument is available since Redis 6.2.
  555. Parsing SET result into:
  556. - BOOL
  557. - String when GET argument is used
  558. """
  559. if options.get("get"):
  560. # Redis will return a getCommand result.
  561. # See `setGenericCommand` in t_string.c
  562. return response
  563. return response and str_if_bytes(response) == "OK"
  564. def string_keys_to_dict(key_string, callback):
  565. return dict.fromkeys(key_string.split(), callback)
  566. _RedisCallbacks = {
  567. **string_keys_to_dict(
  568. "AUTH COPY EXPIRE EXPIREAT HEXISTS HMSET MOVE MSETNX PERSIST PSETEX "
  569. "PEXPIRE PEXPIREAT RENAMENX SETEX SETNX SMOVE",
  570. bool,
  571. ),
  572. **string_keys_to_dict("HINCRBYFLOAT INCRBYFLOAT", float),
  573. **string_keys_to_dict(
  574. "ASKING FLUSHALL FLUSHDB LSET LTRIM MSET PFMERGE READONLY READWRITE "
  575. "RENAME SAVE SELECT SHUTDOWN SLAVEOF SWAPDB WATCH UNWATCH",
  576. bool_ok,
  577. ),
  578. **string_keys_to_dict("XREAD XREADGROUP", parse_xread),
  579. **string_keys_to_dict(
  580. "GEORADIUS GEORADIUSBYMEMBER GEOSEARCH",
  581. parse_geosearch_generic,
  582. ),
  583. **string_keys_to_dict("XRANGE XREVRANGE", parse_stream_list),
  584. "ACL GETUSER": parse_acl_getuser,
  585. "ACL LOAD": bool_ok,
  586. "ACL LOG": parse_acl_log,
  587. "ACL SETUSER": bool_ok,
  588. "ACL SAVE": bool_ok,
  589. "CLIENT INFO": parse_client_info,
  590. "CLIENT KILL": parse_client_kill,
  591. "CLIENT LIST": parse_client_list,
  592. "CLIENT PAUSE": bool_ok,
  593. "CLIENT SETINFO": bool_ok,
  594. "CLIENT SETNAME": bool_ok,
  595. "CLIENT UNBLOCK": bool,
  596. "CLUSTER ADDSLOTS": bool_ok,
  597. "CLUSTER ADDSLOTSRANGE": bool_ok,
  598. "CLUSTER DELSLOTS": bool_ok,
  599. "CLUSTER DELSLOTSRANGE": bool_ok,
  600. "CLUSTER FAILOVER": bool_ok,
  601. "CLUSTER FORGET": bool_ok,
  602. "CLUSTER INFO": parse_cluster_info,
  603. "CLUSTER MEET": bool_ok,
  604. "CLUSTER NODES": parse_cluster_nodes,
  605. "CLUSTER REPLICAS": parse_cluster_nodes,
  606. "CLUSTER REPLICATE": bool_ok,
  607. "CLUSTER RESET": bool_ok,
  608. "CLUSTER SAVECONFIG": bool_ok,
  609. "CLUSTER SET-CONFIG-EPOCH": bool_ok,
  610. "CLUSTER SETSLOT": bool_ok,
  611. "CLUSTER SLAVES": parse_cluster_nodes,
  612. "COMMAND": parse_command,
  613. "CONFIG RESETSTAT": bool_ok,
  614. "CONFIG SET": bool_ok,
  615. "FUNCTION DELETE": bool_ok,
  616. "FUNCTION FLUSH": bool_ok,
  617. "FUNCTION RESTORE": bool_ok,
  618. "GEODIST": float_or_none,
  619. "HSCAN": parse_hscan,
  620. "INFO": parse_info,
  621. "LASTSAVE": timestamp_to_datetime,
  622. "MEMORY PURGE": bool_ok,
  623. "MODULE LOAD": bool,
  624. "MODULE UNLOAD": bool,
  625. "PING": lambda r: str_if_bytes(r) == "PONG",
  626. "PUBSUB NUMSUB": parse_pubsub_numsub,
  627. "PUBSUB SHARDNUMSUB": parse_pubsub_numsub,
  628. "QUIT": bool_ok,
  629. "SET": parse_set_result,
  630. "SCAN": parse_scan,
  631. "SCRIPT EXISTS": lambda r: list(map(bool, r)),
  632. "SCRIPT FLUSH": bool_ok,
  633. "SCRIPT KILL": bool_ok,
  634. "SCRIPT LOAD": str_if_bytes,
  635. "SENTINEL CKQUORUM": bool_ok,
  636. "SENTINEL FAILOVER": bool_ok,
  637. "SENTINEL FLUSHCONFIG": bool_ok,
  638. "SENTINEL GET-MASTER-ADDR-BY-NAME": parse_sentinel_get_master,
  639. "SENTINEL MONITOR": bool_ok,
  640. "SENTINEL RESET": bool_ok,
  641. "SENTINEL REMOVE": bool_ok,
  642. "SENTINEL SET": bool_ok,
  643. "SLOWLOG GET": parse_slowlog_get,
  644. "SLOWLOG RESET": bool_ok,
  645. "SORT": sort_return_tuples,
  646. "SSCAN": parse_scan,
  647. "TIME": lambda x: (int(x[0]), int(x[1])),
  648. "XAUTOCLAIM": parse_xautoclaim,
  649. "XCLAIM": parse_xclaim,
  650. "XGROUP CREATE": bool_ok,
  651. "XGROUP DESTROY": bool,
  652. "XGROUP SETID": bool_ok,
  653. "XINFO STREAM": parse_xinfo_stream,
  654. "XPENDING": parse_xpending,
  655. "ZSCAN": parse_zscan,
  656. }
  657. _RedisCallbacksRESP2 = {
  658. **string_keys_to_dict(
  659. "SDIFF SINTER SMEMBERS SUNION", lambda r: r and set(r) or set()
  660. ),
  661. **string_keys_to_dict(
  662. "ZDIFF ZINTER ZPOPMAX ZPOPMIN ZRANGE ZRANGEBYSCORE ZRANK ZREVRANGE "
  663. "ZREVRANGEBYSCORE ZREVRANK ZUNION",
  664. zset_score_pairs,
  665. ),
  666. **string_keys_to_dict("ZINCRBY ZSCORE", float_or_none),
  667. **string_keys_to_dict("BGREWRITEAOF BGSAVE", lambda r: True),
  668. **string_keys_to_dict("BLPOP BRPOP", lambda r: r and tuple(r) or None),
  669. **string_keys_to_dict(
  670. "BZPOPMAX BZPOPMIN", lambda r: r and (r[0], r[1], float(r[2])) or None
  671. ),
  672. "ACL CAT": lambda r: list(map(str_if_bytes, r)),
  673. "ACL GENPASS": str_if_bytes,
  674. "ACL HELP": lambda r: list(map(str_if_bytes, r)),
  675. "ACL LIST": lambda r: list(map(str_if_bytes, r)),
  676. "ACL USERS": lambda r: list(map(str_if_bytes, r)),
  677. "ACL WHOAMI": str_if_bytes,
  678. "CLIENT GETNAME": str_if_bytes,
  679. "CLIENT TRACKINGINFO": lambda r: list(map(str_if_bytes, r)),
  680. "CLUSTER GETKEYSINSLOT": lambda r: list(map(str_if_bytes, r)),
  681. "COMMAND GETKEYS": lambda r: list(map(str_if_bytes, r)),
  682. "CONFIG GET": parse_config_get,
  683. "DEBUG OBJECT": parse_debug_object,
  684. "GEOHASH": lambda r: list(map(str_if_bytes, r)),
  685. "GEOPOS": lambda r: list(
  686. map(lambda ll: (float(ll[0]), float(ll[1])) if ll is not None else None, r)
  687. ),
  688. "HGETALL": lambda r: r and pairs_to_dict(r) or {},
  689. "MEMORY STATS": parse_memory_stats,
  690. "MODULE LIST": lambda r: [pairs_to_dict(m) for m in r],
  691. "RESET": str_if_bytes,
  692. "SENTINEL MASTER": parse_sentinel_master,
  693. "SENTINEL MASTERS": parse_sentinel_masters,
  694. "SENTINEL SENTINELS": parse_sentinel_slaves_and_sentinels,
  695. "SENTINEL SLAVES": parse_sentinel_slaves_and_sentinels,
  696. "STRALGO": parse_stralgo,
  697. "XINFO CONSUMERS": parse_list_of_dicts,
  698. "XINFO GROUPS": parse_list_of_dicts,
  699. "ZADD": parse_zadd,
  700. "ZMSCORE": parse_zmscore,
  701. }
  702. _RedisCallbacksRESP3 = {
  703. **string_keys_to_dict(
  704. "ZRANGE ZINTER ZPOPMAX ZPOPMIN ZRANGEBYSCORE ZREVRANGE ZREVRANGEBYSCORE "
  705. "ZUNION HGETALL XREADGROUP",
  706. lambda r, **kwargs: r,
  707. ),
  708. **string_keys_to_dict("XREAD XREADGROUP", parse_xread_resp3),
  709. "ACL LOG": lambda r: [
  710. {str_if_bytes(key): str_if_bytes(value) for key, value in x.items()} for x in r
  711. ]
  712. if isinstance(r, list)
  713. else bool_ok(r),
  714. "COMMAND": parse_command_resp3,
  715. "CONFIG GET": lambda r: {
  716. str_if_bytes(key)
  717. if key is not None
  718. else None: str_if_bytes(value)
  719. if value is not None
  720. else None
  721. for key, value in r.items()
  722. },
  723. "MEMORY STATS": lambda r: {str_if_bytes(key): value for key, value in r.items()},
  724. "SENTINEL MASTER": parse_sentinel_state_resp3,
  725. "SENTINEL MASTERS": parse_sentinel_masters_resp3,
  726. "SENTINEL SENTINELS": parse_sentinel_slaves_and_sentinels_resp3,
  727. "SENTINEL SLAVES": parse_sentinel_slaves_and_sentinels_resp3,
  728. "STRALGO": lambda r, **options: {
  729. str_if_bytes(key): str_if_bytes(value) for key, value in r.items()
  730. }
  731. if isinstance(r, dict)
  732. else str_if_bytes(r),
  733. "XINFO CONSUMERS": lambda r: [
  734. {str_if_bytes(key): value for key, value in x.items()} for x in r
  735. ],
  736. "XINFO GROUPS": lambda r: [
  737. {str_if_bytes(key): value for key, value in d.items()} for d in r
  738. ],
  739. }