Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
"""
kwargs = {}
if flags is not None:
kwargs['flags'] = flags
data = bytes(data)
total_bytes_sent = 0
while total_bytes_sent < len(data):
try:
bytes_sent = self.socket.send(data[total_bytes_sent:], **kwargs)
except OSError:
self._socket = self.host = self.port = None
raise
if bytes_sent == 0:
self.socket.close()
raise SocketError('Socket connection broken.')
total_bytes_sent += bytes_sent
def _recv(self, buffersize, flags=None) -> bytes:
"""
Handle socket data reading.
"""
kwargs = {}
if flags is not None:
kwargs['flags'] = flags
chunks = []
bytes_rcvd = 0
while bytes_rcvd < buffersize:
chunk = self.socket.recv(buffersize-bytes_rcvd, **kwargs)
if chunk == b'':
self.socket.close()
raise SocketError('Socket connection broken.')
chunks.append(chunk)
bytes_rcvd += len(chunk)
return b''.join(chunks)
def recv(self, buffersize, flags=None) -> bytes:
"""
Receive data from socket or read-ahead buffer.
:param buffersize: bytes to receive,
:param flags: (optional) OS-specific flags,
:return: data received.
"""
pref_size = len(self.prefetch)
if buffersize > pref_size:
result = self.prefetch
self.prefetch = b''
try:
result += self._recv(buffersize-pref_size, flags)
except (SocketError, OSError):
self._socket = self.host = self.port = None
raise
return result
else:
result = self.prefetch[:buffersize]
self.prefetch = self.prefetch[buffersize:]
return result
client.connect(nodes)
print('Connected to {}'.format(client))
my_cache = client.get_or_create_cache({
PROP_NAME: 'my_cache',
PROP_CACHE_MODE: CacheMode.REPLICATED,
})
my_cache.put('test_key', 0)
# abstract main loop
while True:
try:
# do the work
test_value = my_cache.get('test_key')
my_cache.put('test_key', test_value + 1)
except (OSError, SocketError) as e:
# recover from error (repeat last command, check data
# consistency or just continue − depends on the task)
print('Error: {}'.format(e))
print('Last value: {}'.format(my_cache.get('test_key')))
print('Reconnected to {}'.format(client))