backup: fix flake8 code nits

This commit is contained in:
Michael Schmoock
2022-12-27 13:52:45 +01:00
committed by Christian Decker
parent 7953dc0011
commit 7f18073a3a
6 changed files with 53 additions and 25 deletions

View File

@@ -8,6 +8,7 @@ import zlib
from backend import Change
class PacketType:
CHANGE = 0x01
SNAPSHOT = 0x02
@@ -21,8 +22,10 @@ class PacketType:
COMPACT = 0x0a
COMPACT_RES = 0x0b
PKT_CHANGE_TYPES = {PacketType.CHANGE, PacketType.SNAPSHOT}
def recvall(sock: socket.socket, n: int) -> bytearray:
'''Receive exactly n bytes from a socket.'''
buf = bytearray(n)
@@ -35,28 +38,32 @@ def recvall(sock: socket.socket, n: int) -> bytearray:
ptr += count
return buf
def send_packet(sock: socket.socket, typ: int, payload: bytes) -> None:
sock.sendall(struct.pack('!BI', typ, len(payload)))
sock.sendall(payload)
def recv_packet(sock: socket.socket) -> Tuple[int, bytes]:
(typ, length) = struct.unpack('!BI', recvall(sock, 5))
payload = recvall(sock, length)
return (typ, payload)
def change_from_packet(typ, payload):
'''Convert a network packet to a Change object.'''
if typ == PacketType.CHANGE:
(version, ) = struct.unpack('!I', payload[0:4])
payload = zlib.decompress(payload[4:])
return Change(version=version, snapshot=None,
transaction=[t.decode('UTF-8') for t in payload.split(b'\x00')])
transaction=[t.decode('UTF-8') for t in payload.split(b'\x00')])
elif typ == PacketType.SNAPSHOT:
(version, ) = struct.unpack('!I', payload[0:4])
payload = zlib.decompress(payload[4:])
return Change(version=version, snapshot=payload, transaction=None)
raise ValueError('Not a change (typ {})'.format(typ))
def packet_from_change(entry):
'''Convert a Change object to a network packet.'''
if entry.snapshot is None: