Exemple #1
0
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()
Exemple #2
0
def handle_default_request(raw_request):
    request = json.loads(raw_request.decode())

    if validate_request(request):
        action_name = request.get('action')
        controller = resolve(action_name)
        if controller:
            try:
                logging.debug(
                    f'Controller {action_name} resolved with request: {request}'
                )
                response = controller(request)
            except Exception as err:
                logging.critical(f'Controller {action_name} error: {err}',
                                 exc_info=err)
                response = make_response(request, 500, 'Internal server error')
        else:
            logging.error(f'Controller {action_name} not found')
            response = make_response(
                request, 404, f'Action with name {action_name} not supported')
    else:
        logging.error(f'Controller wrong request: {request}')
        response = make_response(request, 400, 'wrong request format')

    return json.dumps(response).encode()
Exemple #3
0
def handle_default_request(bytes_request):
    request = json.loads(bytes_request.decode())

    if validate_request(request):
        actions_name = request.get('action')
        controller = resolve(actions_name)
        if controller:
            try:
                logging.info(f'Client send valid request {request}')
                response = controller(request)
            except Exception as err:
                logging.critical(f'Internal server error: {err}')
                response = make_response(request,
                                         500,
                                         data='Internal server error')
        else:
            logging.error(
                f'Controller with action name {actions_name} does not exists')
            response = make_response(request, 404, 'Action not found')
    else:
        logging.error(f'Client send invalid request {request}')
        response = make_response(request, 400, 'Wrong request')

    str_response = json.dumps(response)
    return str_response.encode()
def handle_default_request(raw_request):
    request = json.loads(raw_request.decode())

    if validate_request(request):
        action_name = request.get('action')
        controller = resolve(action_name)
        if controller:
            try:
                logging.debug(
                    'controller: {} resolved with request: {}'.format(
                        action_name, request))
                response = controller(request)
            except Exception as err:
                logging.critical('controller: {} error: {}'.format(
                    action_name, err))
                response = make_response(request, 500, 'internal server error')
        else:
            logging.error('controller: {} not found'.format(action_name))
            response = make_response(
                request, 404,
                'action with name {} not supported'.format(action_name))
    else:
        logging.error('controller wrong request: {}'.format(request))
        response = make_response(request, 400, 'wrong request format')

    return json.dumps(response).encode()
def handle_tcp_request(bytes_request):
    request = json.loads(bytes_request.decode())

    if validate_request(request):
        action = request.get('action')
        controller = resolve(action)
        if controller:
            try:
                response = controller(request)
                logging.debug(f'Client send request {request}')
            except Exception as err:
                response = response = make_response(
                    request, 500, f'Internal server error'
                )
                logging.critical(f'Exception - {err}')
        else:
            response = response = make_response(
                request, 404, f'Action {action} is not supported'
            )
            logging.error(f'Client call action with name {action}')
    else:
        response = make_response(
            request, 400, 'Wrong request'
        )
        logging.error(f'Client send wrong request {request}')

    string_response = json.dumps(response)
    return string_response.encode()
Exemple #6
0
def handle_request(raw_request):
    request = jim.unpack(raw_request)

    action_name = request.get('action')

    if validate_request(request):
        controller = resolve(action_name)
        if controller:
            try:
                response = controller(request)
                if response.get('code') != 200:
                    logging.error('Wrong request format')
                else:
                    logging.info(
                        f'Request is valid and processed by controller')
            except Exception as err:
                logging.critical(err)
                response = make_response(request, 500, 'Internal server error')
        else:
            logging.error(f'Action {action_name} does not exits')
            response = make_404(request)
    else:
        logging.error('Request is not valid')
        response = make_400(request)

    return jim.pack(response)
Exemple #7
0
def handle_default_request(raw_request):
    # в строку потом в словарь
    request = json.loads(raw_request.decode())

    # проходим валидацию
    if validate_request(request):
        action_name = request.get('action')
        # извлекаем контроллер
        controller = resolve(action_name)
        # if action == 'echo':
        if controller:
            try:
                ''' фиксируем debug '''
                logging.debug(
                    f'Controller {action_name} resolved with request: {request}'
                )
                response = controller(request)
            except Exception as err:
                ''' фикусируем критическую ситуацию '''
                logging.critical(f'Controller {action_name} error: {err}')
                response = make_response(request, 500, 'Internal server error')
        else:
            ''' фиксируем симантические ошибки '''
            logging.error(f'Controller {action_name} not found')
            response = make_response(
                request, 404,
                f'Action with name "{action_name}"   not supported')
    else:
        ''' фиксируем симантические ошибки '''
        logging.error(f'Controller wrong request: {request}')
        response = make_response(request, 400, 'Wrong request format!')

    return json.dumps(response).encode()
Exemple #8
0
def handle_default_request(raw_request):
    request = json.loads(raw_request.decode(ENCODING_NAME))

    action_name = request.get('action')

    if validate_request(request):
        controller = resolve(action_name)
        if controller:
            try:
                response = controller(request)
                print('response', response)

                if response.get('code') != 200:
                    logging.error(f'Request is not valid')
                else:
                    logging.info(
                        f'Function { controller.__name__ } was called')
            except Exception as err:
                logging.critical(err, exc_info=True)
                response = make_response(
                    request,
                    500,
                    'Internal server error',
                )
        else:
            logging.error(f'Action { action_name } does not exits')
            response = make_404(request)
    else:
        logging.error(f'Request is not valid')
        response = make_400(request)

    return json.dumps(response).encode(ENCODING_NAME)
Exemple #9
0
def handle_default_request(raw_request):
    request = json.loads(raw_request.decode())

    if validate_request(request):
        action_name = request.get('action')
        controller = resolve(action_name)
        if controller:
            try:
                # print(f'Controller {action_name} resolved with request: {request}')
                logging.debug(
                    f'Controller {action_name} resolved with request: {request}'
                )
                # rec2mongo({'level': 'debug', 'Controller': action_name, 'request': str(request), 'time': str(datetime.now())})
                response = controller(request)
            except Exception as err:
                # print(f'Controller {action_name} error: {err}')
                logging.critical(f'Controller {action_name} error: {err}')
                # rec2mongo({'level': 'critical', 'Controller': action_name, 'error': str(err), 'time': str(datetime.now())})
                response = make_response(request, 500, 'Internal server error')
        else:
            # print(f'Controller {action_name} not found')
            logging.error(f'Controller {action_name} not found')
            # rec2mongo({'level': 'error', 'Controller': action_name, 'error': 'Controller not found', 'time': str(datetime.now())})
            response = make_response(
                request, 404, f'Action with name {action_name} not supported')
    else:
        # print(f'Controller wrong request: {request}')
        logging.error(f'Controller wrong request: {request}')
        # rec2mongo({'level': 'error', 'request': str(request), 'time': str(datetime.now())})
        response = make_response(request, 400, 'wrong request format')

    return json.dumps(response).encode()
def test_make_400():
    request = {
        'time': datetime.now().timestamp(),
        'action': 'now',
        'user': '******'
    }

    is_valid = validate_request(request)

    assert is_valid == True

    request = {'user': '******'}

    is_valid = validate_request(request)

    assert is_valid == False
Exemple #11
0
def check_validate(request, server_actions):
    action_name = request.get('action')

    if validate_request(request):
        controller = resolve(action_name, server_actions)
        if controller:
            try:
                return controller(request)
            except Exception as err:
                logging.critical(err)
                return make_response(request, 500, 'Internal server error')
        else:
            logging.error(f'Action with name { action_name } does not exists')
            return make_404(request)
    else:
        logging.error('Request is not valid')
        return make_400(request)
def main():
    try:
        sock = socket.socket()
        sock.bind((host, port))
        sock.listen(5)
        logging.info(f'Server started with {host}:{port}')
        while True:
            client, address = sock.accept()

            logging.info(f'Client detected {address}')

            b_request = client.recv(settings.BUFFERSIZE)
            request = jim.unpack(b_request)

            action_name = request.get('action')

            if validate_request(request):
                controller = resolve(action_name)
                if controller:
                    try:
                        response = controller(request)
                        if response.get('code') != 200:
                            logging.error('Wrong request format')
                        else:
                            logging.info(
                                f'Request is valid and processed by controller'
                            )
                    except Exception as err:
                        logging.critical(err)
                        response = make_response(request, 500,
                                                 'Internal server error')
                else:
                    logging.error(f'Action {action_name} does not exits')
                    response = make_404(request)
            else:
                logging.error('Request is not valid')
                response = make_400(request)

            response = jim.pack(response)
            logging.info('Send response to client')
            client.sendall(response)
    except KeyboardInterrupt:
        logging.info('Server  closed')
Exemple #13
0
def default_handler(raw_request):

    request = json.loads(raw_request)
    action_name = request.get('action')

    if validate_request(request):
        controller = resolve(action_name)
        if controller:
            try:
                response = controller(request)
            except Exception as err:
                logger.critical(err)
                response = make_response(request, 500, 'Internal server error')
        else:
            logger.error(f'Action with name {action_name} does not exists')
            response = make_404(request)
    else:
        logger.error('request is not valid')
        response = make_400(request)

    return json.dumps(response)
Exemple #14
0
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()
Exemple #15
0
def write_response(client, request):
    response = None
    action_name = request.get('action')

    if validate_request(request):
        controller = resolve(action_name)
        if controller:
            try:
                response = controller(request)
            except Exception as err:
                logging.critical(err, exc_info=True)
                respoonse = make_response(request, 500,
                                          'Internal server error')
        else:
            logging.error(f'Action not found: {action_name}')
            response = make_404(request)
    else:
        logging.error(f'Bad Request: {action_name} request: {request}')
        response = make_400(request)

    response_string = json.dumps(response)
    client.send(response_string.encode('utf-8'))
Exemple #16
0
def handle_tcp_request(client_bytes):
    request = json.loads(client_bytes.decode())

    if(validate_request(request)):
        action = request.get('action')
        controller = resolve(action, INSTALLED_APPS)

        if controller:
            try:
                response = controller(request)
                logging.info(f'Sending server response {response}')
            except Exception as err:
                response = make_response(request, 500, 'Internal server error')
                logging.critical(f'Exception - {err}')    
        else:
            response = make_response(request, 404, f'Action {action} not found')
            logging.error(f'Client call unknown action {action}')
    else:
        response = make_response(request, 400, 'Wrong request')
        logging.error(f'Client sent wrong request {request}')

    return json.dumps(response).encode()
Exemple #17
0
def handle_client_request(request):
    action_name = request.get('action')
    if validate_request(request):
        controller = resolve(action_name)
        if controller:
            try:
                return controller(request)
                # if action_name == 'shutdown_server':
                #     logger.info('Shutdown server')
                #     response_string = json.dumps(response)
                #     client.send(response_string.encode('utf-8'))
                #     break

            except Exception as err:
                logger.critical(err, exc_info=True)
                return make_response(request, 500, 'Internal server error.')
        else:
            logger.error(f'Action not found: {action_name}')
            return make_404(request)
    else:
        logger.error(f'Bad request: {request}')
        return make_400(request)
Exemple #18
0
def handle_tcp_request(bytes_request):

    request = json.loads(bytes_request.decode())

    if validate_request(request):
        action = request.get('action')
        controller = resolve(action)
        if controller:
            try:
                response = controller(request)
                logging.debug(f'Client send request {request}')
            except Exception as err:
                response = make_response(request, 500)
                logging.critical(f'Exception — {err}')
        else:
            logging.critical('Invalid action')
            response = make_response(request, 404)
    else:
        logging.critical('Invalid request')
        response = make_response(request, 404)

    string_response = json.dumps(response)
    return string_response.encode()
Exemple #19
0
def handle_default_request(row_request):
    request = json.loads(row_request.decode(ENCODING))

    server_actions = get_server_actions()
    action_name = request.get('action')

    if validate_request(request):
        controller = resolve(action_name, server_actions)
        if controller:
            try:
                response = controller(request)
            except Exception as err:
                logging.critical(err)
                response = make_response(request, 500, 'Internal server error')
        else:
            logging.error(f'Action with name {action_name} does not exist')
            response = make_404(request)
    else:
        logging.error(f'Request is no valid')
        response = make_400(request)

    row_response = json.dumps(response).encode(ENCODING)
    return row_response
def handle_default_request(raw_request, logger):
    request = json.loads(raw_request.decode())
    print(f'request: {request}')

    if validate_request(request):
        action_name = request.get('action')
        controller = resolve(action_name)
        # -----------------------------------------------
        if controller:

            try:
                logger.debug(
                    f'Controller {controller} resolved with request: {request}'
                )
                # print(f'Controller {controller} resolved with request: {request}')
                # response = make_response(request, 200, request.get('data'))
                response = controller(request)

            except Exception as err:
                logger.critical(f'Controller {controller} error: {err}')
                # print(f'Controller {controller} error: {err}')
                response = make_response(request, 500,
                                         'Internal Server  Error!')
        # ------------------------------------------------
        else:
            logger.error(f'Controller {controller} not found!')
            # print(f'Controller {controller} not found!')
            response = make_response(
                request, 404,
                f'Action with name {action_name} is not supported!')

    else:
        logger.error(f'Wrong request!')
        # print(f'Wrong request!')
        response = make_response(request, 400, 'Wrong request format!')

    return json.dumps(response).encode()
Exemple #21
0
        port = sys.argv[4]

sock = socket.socket()
sock.bind((address, port))
sock.listen(5)

logger = logging.getLogger('server')
logger.info(f'Server start with host:{ address } and port: { port }')
try:
    while True:
        client, address = sock.accept()
        logger.info(f'Client detected {address}')
        data = client.recv(1024)
        request = json.loads(data.decode('utf-8'))

        if validate_request(request):
            action_name = request.get('action')
            controller = resolve(action_name)

            if controller:
                try:
                    response = controller(request)

                    if action_name == 'shutdown_server':
                        logger.info('Shutdown server')
                        response_string = json.dumps(response)
                        client.send(response_string.encode('utf-8'))
                        break

                except Exception as err:
                    logger.critical(err, exc_info=True)
Exemple #22
0
def test_validate_request_false_time(invalid_request_time,
                                     assert_response_false):
    response = validate_request(invalid_request_time)

    assert assert_response_false == response
Exemple #23
0
def test_validate_request_false_action(invalid_request_action,
                                       assert_response_false):
    response = validate_request(invalid_request_action)

    assert assert_response_false == response
Exemple #24
0
def test_validate_request_true(valid_request, assert_response_true):
    response = validate_request(valid_request)

    assert assert_response_true == response
Exemple #25
0
def test_validate_request(initial_request, expected_response):
    actual_response = validate_request(initial_request)
    assert actual_response == expected_response
Exemple #26
0
def test_validate_not_full_request(initial_not_full_request):
    actual_validate_not_full_request = validate_request(initial_not_full_request)
    assert actual_validate_not_full_request == False
Exemple #27
0
def test_validate_full_request(initial_full_request):
    actual_validate_full_request = validate_request(initial_full_request)
    assert actual_validate_full_request == True
Exemple #28
0
def test_invalid_validate_request(invalid_request):
    is_valid = validate_request(invalid_request)
    assert not is_valid
Exemple #29
0
def test_valid_validate_request(valid_request):
    is_valid = validate_request(valid_request)
    assert is_valid
host, port = config.get('host'), config.get('port')
try:
    sock = socket.socket()
    sock.bind((host, port))
    sock.listen(5)

    logging.info(f'Server initiated at: {host}:{port}')

    while True:
        client, (client_host, client_port) = sock.accept()
        logging.info(
            f'Client connected at host: {client_host}, port: {client_port}')
        received_request = client.recv(config.get('buffer_size'))
        received_request = json.loads(received_request.decode())
        if validate_request(received_request):
            action_name = received_request.get('action')
            controller = resolve(action_name)
            if controller:
                try:
                    logging.info('Request OK')
                    response = controller(received_request)
                except Exception as exception:
                    logging.critical(f'Error encountered: {exception}')
                    response = form_response(received_request,
                                             code=500,
                                             data='Server Error')
            else:
                logging.error('Controller not found')
                response = form_response(received_request,
                                         code=404,