class ValuesMapProcessor(asyncio.Protocol): """Count volume of input/output data. """ parser = connection = None def connection_made(self, transport): """Prepare connection. """ peername = transport.get_extra_info('peername') print('Connection from {}'.format(peername)) self.connection = transport self.parser = CmdParser() def data_received(self, data): """Read/write socket. """ if data[:4] == b"exit": print("Close the client socket") self.connection.close() else: self.parser.fill(data) if self.parser.is_full: answer = "error\n" value = None if self.parser.is_operation_write: code = storage.write(self.parser.get_bytes()) if code: value = "w", code, storage.sum(code) else: code, value = storage.read(self.parser.get_bytes()) if code: value = "r", code, value or 0 if value: answer = "{}.{} {:.6f}\n".format(*value) try: self.connection.write(answer.encode()) finally: self.parser.clear() def connection_lost(self, exc): pass
class DataStorage: """Combines the methods of storage. """ data = None def __init__(self): self.data = {} self.parser = CmdParser() def write(self, data: bytes) -> str: """Main write method. """ self.parser.clear() self.parser.fill(data) code, data = self.parser.get_data_fast() if code not in self.data: self.data[code] = CellStorage() self.data[code].extend(data) return code def read(self, data: bytes) -> (str, float): """Main read method. """ self.parser.clear() self.parser.fill(data) result = 0.0 code, data = self.parser.get_data_fast() stor = self.data.get(code) if stor: result = stor.search_variant(data) return code, result def sum(self, code: str) -> float: """Get sum of values by code. """ stor = self.data.get(code) return stor.sum() if stor else 0.0