Skip to content
This repository was archived by the owner on Jan 9, 2024. It is now read-only.

Commit 9eb7f62

Browse files
committed
Code cleanup
1 parent 277aa62 commit 9eb7f62

19 files changed

+200
-161
lines changed

rediscluster/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
# python std lib
44
import logging
5-
import sys
65

76
# rediscluster imports
87
from rediscluster.client import RedisCluster

rediscluster/client.py

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
from __future__ import unicode_literals
33

44
# python std lib
5-
import datetime
65
import json
76
import logging
87
import random
@@ -45,11 +44,10 @@
4544
from redis import Redis
4645
from redis.client import list_or_args, parse_info
4746
from redis.connection import Connection, SSLConnection
48-
from redis._compat import iteritems, basestring, izip, nativestr, long
47+
from redis._compat import iteritems, nativestr, long
4948
from redis.exceptions import (
5049
BusyLoadingError,
5150
ConnectionError,
52-
DataError,
5351
RedisError,
5452
ResponseError,
5553
TimeoutError,
@@ -211,7 +209,7 @@ class RedisCluster(Redis):
211209
"ZCARD",
212210
"ZCOUNT",
213211
"ZRANGE",
214-
"ZSCORE"
212+
"ZSCORE",
215213
]
216214

217215
RESULT_CALLBACKS = dict_merge(
@@ -377,7 +375,7 @@ def __init__(self, host=None, port=None, startup_nodes=None, max_connections=Non
377375
nodemanager_follow_cluster=nodemanager_follow_cluster,
378376
connection_class=connection_class,
379377
host_port_remap=host_port_remap,
380-
**kwargs
378+
**kwargs,
381379
)
382380

383381
super(RedisCluster, self).__init__(connection_pool=pool, **kwargs)
@@ -447,7 +445,7 @@ def pubsub(self, **kwargs):
447445
"""
448446
return ClusterPubSub(self.connection_pool, **kwargs)
449447

450-
def pipeline(self, transaction=None, shard_hint=None):
448+
def pipeline(self, transaction=None, shard_hint=None, read_from_replicas=False):
451449
"""
452450
Cluster impl:
453451
Pipelines do not work in cluster mode the same way they do in normal mode.
@@ -466,6 +464,7 @@ def pipeline(self, transaction=None, shard_hint=None):
466464
result_callbacks=self.result_callbacks,
467465
response_callbacks=self.response_callbacks,
468466
cluster_down_retry_attempts=self.cluster_down_retry_attempts,
467+
read_from_replicas=read_from_replicas,
469468
)
470469

471470
def transaction(self, *args, **kwargs):
@@ -492,7 +491,7 @@ def _determine_slot(self, *args):
492491

493492
if command in ['XREADGROUP', 'XREAD']:
494493
stream_idx = args.index(b'STREAMS')
495-
keys_ids = list(args[stream_idx + 1: ])
494+
keys_ids = list(args[stream_idx + 1:])
496495
idx_split = len(keys_ids) // 2
497496
keys = keys_ids[: idx_split]
498497
slots = {self.connection_pool.nodes.keyslot(key) for key in keys}
@@ -642,10 +641,10 @@ def _execute_command(self, *args, **kwargs):
642641
# This is the last attempt before we run out of TTL, raise the exception
643642
if ttl == 1:
644643
raise e
645-
except (RedisClusterException, BusyLoadingError) as e:
644+
except (RedisClusterException, BusyLoadingError):
646645
log.exception("RedisClusterException || BusyLoadingError")
647646
raise
648-
except ConnectionError as e:
647+
except ConnectionError:
649648
log.exception("ConnectionError")
650649

651650
connection.disconnect()
@@ -667,8 +666,7 @@ def _execute_command(self, *args, **kwargs):
667666
self.connection_pool.nodes.increment_reinitialize_counter(
668667
count=self.connection_pool.nodes.reinitialize_steps,
669668
)
670-
671-
except TimeoutError as e:
669+
except TimeoutError:
672670
log.exception("TimeoutError")
673671

674672
if ttl < self.RedisClusterRequestTTL / 2:
@@ -695,7 +693,7 @@ def _execute_command(self, *args, **kwargs):
695693

696694
node = self.connection_pool.nodes.set_node(e.host, e.port, server_type='master')
697695
self.connection_pool.nodes.slots[e.slot_id][0] = node
698-
except TryAgainError as e:
696+
except TryAgainError:
699697
log.exception("TryAgainError")
700698

701699
if ttl < self.RedisClusterRequestTTL / 2:
@@ -733,7 +731,7 @@ def _execute_command_on_nodes(self, nodes, *args, **kwargs):
733731

734732
connection.send_command(*args)
735733
res[node["name"]] = self.parse_response(connection, command, **kwargs)
736-
except ClusterDownError as e:
734+
except ClusterDownError:
737735
self.connection_pool.disconnect()
738736
self.connection_pool.reset()
739737
self.refresh_table_asap = True

rediscluster/connection.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ def on_connect(self):
102102

103103
if nativestr(self.read_response()) != 'OK':
104104
raise ConnectionError('READONLY command failed')
105-
105+
106106

107107
class ClusterConnectionPool(ConnectionPool):
108108
"""
@@ -328,7 +328,7 @@ def get_connection_by_slot(self, slot):
328328

329329
try:
330330
return self.get_connection_by_node(self.get_node_by_slot(slot))
331-
except (KeyError, RedisClusterException) as exc:
331+
except (KeyError, RedisClusterException):
332332
return self.get_random_connection()
333333

334334
def get_connection_by_node(self, node):
@@ -353,7 +353,7 @@ def get_master_node_by_slot(self, slot):
353353
"""
354354
try:
355355
return self.nodes.slots[slot][0]
356-
except KeyError as ke:
356+
except KeyError:
357357
raise SlotNotCoveredError('Slot "{slot}" not covered by the cluster. "skip_full_coverage_check={skip_full_coverage_check}"'.format(
358358
slot=slot, skip_full_coverage_check=self.nodes._skip_full_coverage_check,
359359
))
@@ -397,11 +397,11 @@ class ClusterBlockingConnectionPool(ClusterConnectionPool):
397397
# not available.
398398
>>> pool = ClusterBlockingConnectionPool(timeout=5)
399399
"""
400+
400401
def __init__(self, startup_nodes=None, init_slot_cache=True, connection_class=None,
401402
max_connections=None, max_connections_per_node=False, reinitialize_steps=None,
402403
skip_full_coverage_check=False, nodemanager_follow_cluster=False,
403404
timeout=20, **connection_kwargs):
404-
405405
self.timeout = timeout
406406

407407
super(ClusterBlockingConnectionPool, self).__init__(
@@ -413,7 +413,7 @@ def __init__(self, startup_nodes=None, init_slot_cache=True, connection_class=No
413413
reinitialize_steps=reinitialize_steps,
414414
skip_full_coverage_check=skip_full_coverage_check,
415415
nodemanager_follow_cluster=nodemanager_follow_cluster,
416-
**connection_kwargs
416+
**connection_kwargs,
417417
)
418418

419419
def _blocking_pool_factory(self):
@@ -557,7 +557,8 @@ def __init__(self, startup_nodes=None, init_slot_cache=True, connection_class=No
557557
max_connections=max_connections,
558558
readonly=True,
559559
nodemanager_follow_cluster=nodemanager_follow_cluster,
560-
**connection_kwargs)
560+
**connection_kwargs,
561+
)
561562

562563
self.master_node_commands = ('SCAN', 'SSCAN', 'HSCAN', 'ZSCAN')
563564

rediscluster/exceptions.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ class ClusterCrossSlotError(ResponseError):
4444
class ClusterDownError(ClusterError, ResponseError):
4545
"""
4646
"""
47+
4748
def __init__(self, resp):
4849
self.args = (resp, )
4950
self.message = resp
@@ -72,6 +73,7 @@ def __init__(self, resp):
7273
class TryAgainError(ResponseError):
7374
"""
7475
"""
76+
7577
def __init__(self, *args, **kwargs):
7678
pass
7779

@@ -81,6 +83,7 @@ class MovedError(AskError):
8183
"""
8284
pass
8385

86+
8487
class MasterDownError(ClusterDownError):
8588
"""
8689
"""

rediscluster/nodemanager.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
class NodeManager(object):
2222
"""
2323
"""
24-
RedisClusterHashSlots = 16384
24+
REDIS_CLUSTER_HASH_SLOTS = 16384
2525

2626
def __init__(self, startup_nodes=None, reinitialize_steps=None, skip_full_coverage_check=False, nodemanager_follow_cluster=False,
2727
host_port_remap=None, **connection_kwargs):
@@ -86,7 +86,7 @@ def _validate_host_port_remap(self, host_port_remap):
8686
socket.inet_aton(item.get('to_host', '0.0.0.0').strip())
8787
except socket.error:
8888
raise RedisClusterConfigError("Both from_host and to_host in host_port_remap rule must be a valid ip address")
89-
if len(item.get('from_host', '0.0.0.0').split('.')) < 4 or len(item.get('to_host', '0.0.0.0').split('.')) < 4 :
89+
if len(item.get('from_host', '0.0.0.0').split('.')) < 4 or len(item.get('to_host', '0.0.0.0').split('.')) < 4:
9090
raise RedisClusterConfigError(
9191
"Both from_host and to_host in host_port_remap rule must must have all octets specified")
9292

@@ -110,7 +110,7 @@ def keyslot(self, key):
110110
if end > -1 and end != start + 1:
111111
k = k[start + 1:end]
112112

113-
return crc16(k) % self.RedisClusterHashSlots
113+
return crc16(k) % self.REDIS_CLUSTER_HASH_SLOTS
114114

115115
def node_from_slot(self, slot):
116116
"""
@@ -286,7 +286,7 @@ def initialize(self):
286286
need_full_slots_coverage = self.cluster_require_full_coverage(nodes_cache)
287287

288288
# Validate if all slots are covered or if we should try next startup node
289-
for i in range(0, self.RedisClusterHashSlots):
289+
for i in range(0, self.REDIS_CLUSTER_HASH_SLOTS):
290290
if i not in tmp_slots and need_full_slots_coverage:
291291
all_slots_covered = False
292292

@@ -299,7 +299,7 @@ def initialize(self):
299299

300300
if not all_slots_covered:
301301
raise RedisClusterException("All slots are not covered after query all startup_nodes. {0} of {1} covered...".format(
302-
len(tmp_slots), self.RedisClusterHashSlots))
302+
len(tmp_slots), self.REDIS_CLUSTER_HASH_SLOTS))
303303

304304
# Set the tmp variables to the real variables
305305
self.slots = tmp_slots

rediscluster/pipeline.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ def send_cluster_commands(self, stack, raise_on_error=True, allow_redirections=T
156156
157157
It will try the number of times specified by the config option "self.cluster_down_retry_attempts"
158158
which defaults to 3 unless manually configured.
159-
159+
160160
If it reaches the number of times, the command will raises ClusterDownException.
161161
"""
162162
for _ in range(0, self.cluster_down_retry_attempts):

rediscluster/utils.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,8 @@
11
# -*- coding: utf-8 -*-
22
from socket import gethostbyaddr
3-
from functools import wraps
43

54
# rediscluster imports
6-
from .exceptions import (
7-
RedisClusterException, ClusterDownError
8-
)
5+
from .exceptions import RedisClusterException
96

107
# 3rd party imports
118
from redis._compat import basestring, nativestr

tests/conftest.py

Lines changed: 27 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22

33
# python std lib
44
import os
5+
import random
56
import sys
6-
import json
77

88
# rediscluster imports
99
from rediscluster import RedisCluster
@@ -13,7 +13,6 @@
1313
from distutils.version import StrictVersion
1414
from mock import Mock
1515
from redis import Redis
16-
from redis.exceptions import ResponseError
1716

1817
# put our path in front so we can be sure we are testing locally not against the global package
1918
basepath = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -223,35 +222,38 @@ def mock_cluster_resp_int(request, **kwargs):
223222
@pytest.fixture()
224223
def mock_cluster_resp_info(request, **kwargs):
225224
r = _get_client(RedisCluster, request, **kwargs)
226-
response = ('cluster_state:ok\r\ncluster_slots_assigned:16384\r\n'
227-
'cluster_slots_ok:16384\r\ncluster_slots_pfail:0\r\n'
228-
'cluster_slots_fail:0\r\ncluster_known_nodes:7\r\n'
229-
'cluster_size:3\r\ncluster_current_epoch:7\r\n'
230-
'cluster_my_epoch:2\r\ncluster_stats_messages_sent:170262\r\n'
231-
'cluster_stats_messages_received:105653\r\n')
225+
response = (
226+
'cluster_state:ok\r\ncluster_slots_assigned:16384\r\n'
227+
'cluster_slots_ok:16384\r\ncluster_slots_pfail:0\r\n'
228+
'cluster_slots_fail:0\r\ncluster_known_nodes:7\r\n'
229+
'cluster_size:3\r\ncluster_current_epoch:7\r\n'
230+
'cluster_my_epoch:2\r\ncluster_stats_messages_sent:170262\r\n'
231+
'cluster_stats_messages_received:105653\r\n'
232+
)
232233
return _gen_cluster_mock_resp(r, response)
233234

234235

235236
@pytest.fixture()
236237
def mock_cluster_resp_nodes(request, **kwargs):
237238
r = _get_client(RedisCluster, request, **kwargs)
238-
response = ('c8253bae761cb1ecb2b61857d85dfe455a0fec8b 172.17.0.7:7006 '
239-
'slave aa90da731f673a99617dfe930306549a09f83a6b 0 '
240-
'1447836263059 5 connected\n'
241-
'9bd595fe4821a0e8d6b99d70faa660638a7612b3 172.17.0.7:7008 '
242-
'master - 0 1447836264065 0 connected\n'
243-
'aa90da731f673a99617dfe930306549a09f83a6b 172.17.0.7:7003 '
244-
'myself,master - 0 0 2 connected 5461-10922\n'
245-
'1df047e5a594f945d82fc140be97a1452bcbf93e 172.17.0.7:7007 '
246-
'slave 19efe5a631f3296fdf21a5441680f893e8cc96ec 0 '
247-
'1447836262556 3 connected\n'
248-
'4ad9a12e63e8f0207025eeba2354bcf4c85e5b22 172.17.0.7:7005 '
249-
'master - 0 1447836262555 7 connected 0-5460\n'
250-
'19efe5a631f3296fdf21a5441680f893e8cc96ec 172.17.0.7:7004 '
251-
'master - 0 1447836263562 3 connected 10923-16383\n'
252-
'fbb23ed8cfa23f17eaf27ff7d0c410492a1093d6 172.17.0.7:7002 '
253-
'master,fail - 1447829446956 1447829444948 1 disconnected\n'
254-
)
239+
response = (
240+
'c8253bae761cb1ecb2b61857d85dfe455a0fec8b 172.17.0.7:7006 '
241+
'slave aa90da731f673a99617dfe930306549a09f83a6b 0 '
242+
'1447836263059 5 connected\n'
243+
'9bd595fe4821a0e8d6b99d70faa660638a7612b3 172.17.0.7:7008 '
244+
'master - 0 1447836264065 0 connected\n'
245+
'aa90da731f673a99617dfe930306549a09f83a6b 172.17.0.7:7003 '
246+
'myself,master - 0 0 2 connected 5461-10922\n'
247+
'1df047e5a594f945d82fc140be97a1452bcbf93e 172.17.0.7:7007 '
248+
'slave 19efe5a631f3296fdf21a5441680f893e8cc96ec 0 '
249+
'1447836262556 3 connected\n'
250+
'4ad9a12e63e8f0207025eeba2354bcf4c85e5b22 172.17.0.7:7005 '
251+
'master - 0 1447836262555 7 connected 0-5460\n'
252+
'19efe5a631f3296fdf21a5441680f893e8cc96ec 172.17.0.7:7004 '
253+
'master - 0 1447836263562 3 connected 10923-16383\n'
254+
'fbb23ed8cfa23f17eaf27ff7d0c410492a1093d6 172.17.0.7:7002 '
255+
'master,fail - 1447829446956 1447829444948 1 disconnected\n'
256+
)
255257
return _gen_cluster_mock_resp(r, response)
256258

257259

0 commit comments

Comments
 (0)