Skip to content

Commit

Permalink
better error management
Browse files Browse the repository at this point in the history
  • Loading branch information
thefab committed Sep 19, 2014
1 parent 9c8712b commit 6685dad
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 5 deletions.
10 changes: 10 additions & 0 deletions tornadis/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,16 @@ def __init__(self, host='localhost', port=6379, ioloop=None):
self.port = port
self.subscribed = False
self.__ioloop = ioloop or tornado.ioloop.IOLoop.instance()
self.__connection = None

def is_connected(self):
"""Returns True is the client is connected to redis.
Returns:
True if the client if connected to redis.
"""
return (self.__connection is not None) and \
(self.__connection.connected)

@tornado.gen.coroutine
def connect(self):
Expand Down
17 changes: 13 additions & 4 deletions tornadis/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,14 @@ def connect(self):
Returns:
Future: a Future object with no specific result.
Raises:
ConnectionError: when there is a connection error
"""
self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.__stream = tornado.iostream.IOStream(self.__socket,
io_loop=self.__ioloop)
future = self.__stream.connect((self.host, self.port))
if future is None:
raise ConnectionError("can't connect to %s:%i" % (self.host,
self.port))
try:
yield future
except:
Expand All @@ -60,6 +60,7 @@ def disconnect(self):
self.__stream.close()
self.connected = False

@tornado.gen.coroutine
def write(self, data):
"""Writes some data to the host:port
Expand All @@ -69,8 +70,16 @@ def write(self, data):
Returns:
Future: a Future object "resolved" when the data is written
on the socket (no specific result)
Raises:
ConnectionError: when there is a connection error
"""
return self.__stream.write(data)
try:
result = yield self.__stream.write(data)
except:
self.connected = False
raise ConnectionError("can't write to socket")
raise tornado.gen.Return(result)

def register_read_until_close_callback(self, callback=None,
streaming_callback=None):
Expand Down
6 changes: 5 additions & 1 deletion tornadis/pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,12 @@ def get_connected_client(self):
"""
if self.__sem is not None:
yield self.__sem.acquire()
client = None
try:
client = self.__pool.popleft()
while True:
client = self.__pool.popleft()
if client.is_connected():
break
except IndexError:
client = self._make_client()
yield client.connect()
Expand Down

0 comments on commit 6685dad

Please sign in to comment.