diff options
| author | Андрей Гущин <saintruler@gmail.com> | 2019-06-06 10:02:41 +0300 |
|---|---|---|
| committer | Андрей Гущин <saintruler@gmail.com> | 2019-06-06 10:02:41 +0300 |
| commit | 3cfb10729201b806b09a12de4eef6abb3b71aad5 (patch) | |
| tree | 06d5fd4b269d40dc0c5863e6c419cb95144db560 /day4/task3/server.py | |
| parent | 5191aa270d852da42ff8adbd630daeb7fb82fa23 (diff) | |
| parent | 4a3db50d7df0f636ef824637d33330543e9044b2 (diff) | |
День 4, задача 3
See merge request saintruler/trainee!18
Diffstat (limited to 'day4/task3/server.py')
| -rw-r--r-- | day4/task3/server.py | 100 |
1 files changed, 100 insertions, 0 deletions
diff --git a/day4/task3/server.py b/day4/task3/server.py new file mode 100644 index 0000000..3aea050 --- /dev/null +++ b/day4/task3/server.py @@ -0,0 +1,100 @@ +import socket +import struct +from db import search_by_date +import re +import json +import time + + +HOST, PORT = ADDR = '0.0.0.0', 6000 +DATATYPE_SIZE = 4 # int + + +def pack_data(data): + encoded = data.encode() + return struct.pack('I', len(encoded)) + encoded + + +def handle_request(data): + match = re.match(r'(\d+):?(\d+)?:?(\d+)?-(.*)', data) + if match: + *date, msg = match.groups() + + t = time.time() + found = search_by_date(*map(lambda i: int(i) if i is not None else i, date), msg) + print(f'Search took {time.time() - t} seconds') + return pack_data(json.dumps(found)) + + else: + print('String not matched.') + return pack_data(json.dumps([])) + + +def get_data(connection): + buffer = b'' + # Считываем размер пакета + while len(buffer) < DATATYPE_SIZE: + data = connection.recv(DATATYPE_SIZE - len(buffer)) + if not data: + raise ConnectionError('Connection was closed') + + buffer += data + + size_packed, buffer = buffer[:DATATYPE_SIZE], buffer[DATATYPE_SIZE:] + if not size_packed: + raise ConnectionError('Connection was closed') + + (size,) = struct.unpack('I', size_packed) + data = connection.recv(size - len(buffer)) + return buffer + data + + +def handle_connection(connection, address): + while True: + try: + data = get_data(connection) + + except ConnectionResetError: + print(f'Connection with {address[0]} was unexpectedly closed') + break + + except ConnectionError: + print(f'Connection with {address[0]} was ended') + break + + except KeyboardInterrupt: + raise KeyboardInterrupt() + + else: + if not data: + print(f'Connection with {address[0]} was ended') + break + response = handle_request(data.decode()) + connection.sendall(response) + + +def main(): + sock = socket.socket() + sock.bind(ADDR) + sock.listen(5) + + while True: + print('Listening for new connections...') + try: + connection, address = sock.accept() + print(f'Got a connection from {address[0]}') + handle_connection(connection, address) + + except KeyboardInterrupt: + print('Stopping server...') + sock.close() + print('Server stopped') + break + + +if __name__ == '__main__': + success = db.init('otrs_error.log') + if not success: + print('Не удалось инициализировать базу данных. Завершаем работу...') + else: + main() |