def handle_tcp_req(bytes_req, action_mapping): """ Функция формирования ответа :param bytes_req: bytes :param action_mapping: dict :return: bytes """ req = json.loads(bytes_req) if validate_request(req): action = req.get('action') controller = action_mapping.get(action) if controller: try: logging.debug(f'Request: {bytes_req.decode()}') resp = controller(req) except Exception as err: if err.args[0] == 401: resp = make_401(req) logging.error(f'{err}: Unauthorized. Please enter the password') else: resp = make_500(req) logging.critical(err) else: resp = make_404(req) logging.error(f'404: Wrong action: {req}') else: resp = make_400(req, 'Request is not valid') logging.error(f'400: Wrong request: {req}') str_resp = json.dumps(resp) return str_resp.encode()
def handle_tcp_request(bytes_request, action_mapping): request = json.loads(bytes_request) if validate_request(request): action = request.get('action') controller = action_mapping.get(action) if controller: try: response = controller(request) logging.debug(f'Request: {bytes_request.decode()}') except Exception as err: response = make_500(request) logging.critical(err) else: response = make_404(request) logging.error(f'Action with name {action} not found') else: response = make_404(request, 'Request is not valid') logging.error(f'Wrong request: {request}') string_response = json.dumps(response) return string_response.encode()
while True: client, (client_host, client_port) = sock.accept() print(f'Client {client_host}:{client_port} was connected') bytes_request = client.recv(buffersize) request = json.loads(bytes_request) if validate_request(request): action = request.get('action') controller = action_mapping.get(action) if controller: try: response = controller(request) print(f'Request: {bytes_request.decode()}') except Exception as err: response = make_500(request) print(err) else: response = make_404(request) else: response = make_404(request, 'Request is not valid') print(f'Wrong request: {request}') string_response = json.dumps(response) client.send(string_response.encode()) client.close() except KeyboardInterrupt: print('Server shutdown')
def test_make_response_500(initial_request, expected_time, code_500): response = make_500(initial_request, expected_time) code = response.get('code') assert code == code_500
def test_make_500(initial_request, code_500, expected_time): response = make_500(initial_request, date=expected_time) assert response.get('code') == code_500
def test_data_make_500(): response = make_500(REQUEST, date=TIME) action = response.get('data') assert action == DATA_505
def test_code_make_500(): response = make_500(REQUEST, date=TIME) action = response.get('code') assert action == 500