Ejemplo n.º 1
0
    def test_format_response(self):
        with self.app.test_request_context():
            result = format_response(200, 'Unity test of message formatter')
            self.assertEqual(result.status, '200 OK')
            self.assertEqual(json.loads(result.response[0])[
                             'message'], 'Unity test of message formatter')

            result = format_response(202)
            self.assertEqual(result.status, '202 ACCEPTED')
            self.assertEqual(json.loads(result.response[0])['message'], 'ok')

            result = format_response(404)
            self.assertEqual(result.status, '404 NOT FOUND')
            self.assertEqual(json.loads(result.response[0])[
                             'message'], 'Request failed')
Ejemplo n.º 2
0
def flask_import_data():
    try:
        LOGGER.info(f" Starting importing data...")

        # retrieve the authorization token
        token = retrieve_auth_token(request)

        # retrieve header and body of request
        content_type = request.headers.get('Content-Type')
        data = request.data

        result = ImportHandler.import_data(data, token, content_type)

        LOGGER.info(f" Imported data!")

        return make_response(jsonify(result), 201)

    except ValidationError as e:
        results = {'message': 'failed to parse attr', 'errors': e}
        LOGGER.error(f" {e}")
        return make_response(jsonify(results), 400)
    except HTTPRequestError as error:
        LOGGER.error(f" {error.message}")
        if isinstance(error.message, dict):
            return make_response(jsonify(error.message), error.error_code)
        return format_response(error.error_code, error.message)
Ejemplo n.º 3
0
def flask_create_device():
    """
    Creates and configures the given device (in json).

    Check API description for more information about request parameters and
    headers.
    """
    try:
        # retrieve the authorization token
        token = retrieve_auth_token(request)

        params = {
            'count': request.args.get('count', '1'),
            'verbose': request.args.get('verbose', 'false'),
            'content_type': request.headers.get('Content-Type'),
            'data': request.data
        }

        result = DeviceHandler.create_device(params, token)
        devices = result.get('devices')
        deviceId = devices[0].get('id')
        LOGGER.info(f' Creating a new device with id {deviceId}.')
        return make_response(jsonify(result), 200)
    except HTTPRequestError as e:
        LOGGER.error(f' {e.message} - {e.error_code}.')
        if isinstance(e.message, dict):
            return make_response(jsonify(e.message), e.error_code)

        return format_response(e.error_code, e.message)
Ejemplo n.º 4
0
def flask_copy_psk(device_id, attr_label):
    try:
        # retrieve the authorization token
        token = retrieve_auth_token(request)

        # retrieve the parameters
        if ((not 'from_dev_id' in request.args.keys()) or
            (not 'from_attr_label' in request.args.keys())):
            raise HTTPRequestError(400, "Missing mandatory parameter: from_dev_id "
                "or/and from_attr_label")

        from_dev_id = request.args['from_dev_id']
        from_attr_label = request.args['from_attr_label']

        DeviceHandler.copy_psk(token,
                                from_dev_id,
                                from_attr_label,
                                device_id,
                                attr_label)

        return make_response("", 204)
    except HTTPRequestError as e:
        if isinstance(e.message, dict):
            return make_response(jsonify(e.message), e.error_code)

        return format_response(e.error_code, e.message)
Ejemplo n.º 5
0
def flask_get_templates():
    try:
        # retrieve the authorization token
        token = retrieve_auth_token(request)

        # retrieve pagination
        page_number, per_page = get_pagination(request)

        params = {
            'page_number': page_number,
            'per_page': per_page,
            'sortBy': request.args.get('sortBy', None),
            'attr': request.args.getlist('attr'),
            'attr_type': request.args.getlist('attr_type'),
            'label': request.args.get('label', None),
            'attrs_format': request.args.get('attr_format', 'both')
        }

        result = TemplateHandler.get_templates(params, token)

        for templates in result.get('templates'):
            LOGGER.info(f" Getting template with id {templates.get('id')}")

        return make_response(jsonify(result), 200)

    except ValidationError as e:
        results = {'message': 'failed to parse attr', 'errors': e}
        LOGGER.error(f" {e}")
        return make_response(jsonify(results), 500)

    except HTTPRequestError as e:
        LOGGER.error(f" {e}")
        if isinstance(e.message, dict):
            return make_response(jsonify(e.message), e.error_code)
        return format_response(e.error_code, e.message)
Ejemplo n.º 6
0
def flask_create_template():
    try:
        # retrieve the authorization token
        token = retrieve_auth_token(request)

        params = {
            'content_type': request.headers.get('Content-Type'),
            'data': request.data
        }

        result = TemplateHandler.create_template(params, token)

        LOGGER.info(f"Creating a new template")

        return make_response(jsonify(result), 200)

    except ValidationError as e:
        results = {'message': 'failed to parse attr', 'errors': e}
        LOGGER.error(f" {e}")
        return make_response(jsonify(results), 400)
    except HTTPRequestError as error:
        LOGGER.error(f" {error}")
        if isinstance(error.message, dict):
            return make_response(jsonify(error.message), error.error_code)
        return format_response(error.error_code, error.message)
Ejemplo n.º 7
0
def flask_gen_psk(device_id):
    try:
        # retrieve the authorization token
        token = retrieve_auth_token(request)

        # retrieve the key_length parameter (mandatory)
        if not 'key_length' in request.args.keys():
            raise HTTPRequestError(400, "Missing key_length parameter")
        key_length = int(request.args['key_length'])

        # retrieve the attrs parameter (optional)
        target_attributes = None
        if 'attrs' in request.args.keys():
            target_attributes = request.args['attrs'].split(",")

        result = DeviceHandler.gen_psk(token,
                                       device_id,
                                       key_length,
                                       target_attributes)

        LOGGER.info(f' Successfully generated psk for the device: {device_id}.')
        return make_response(jsonify(result), 200)
    except HTTPRequestError as e:
        LOGGER.error(f' {e.message} - {e.error_code}.')
        if isinstance(e.message, dict):
            return make_response(jsonify(e.message), e.error_code)

        return format_response(e.error_code, e.message)
Ejemplo n.º 8
0
def flask_internal_get_device(device_id):
    try:
        result = DeviceHandler.get_device(request, device_id, True)
        return make_response(jsonify(result), 200)
    except HTTPRequestError as e:
        if isinstance(e.message, dict):
            return make_response(jsonify(e.message), e.error_code)
        else:
            return format_response(e.error_code, e.message)
Ejemplo n.º 9
0
def flask_get_by_template(template_id):
    try:
        result = DeviceHandler.get_by_template(request, template_id)
        return make_response(jsonify(result), 200)
    except HTTPRequestError as e:
        if isinstance(e.message, dict):
            return make_response(jsonify(e.message), e.error_code)
        else:
            return format_response(e.error_code, e.message)
Ejemplo n.º 10
0
def flask_update_device(device_id):
    try:
        results = DeviceHandler.update_device(request, device_id)
        return make_response(jsonify(results), 200)
    except HTTPRequestError as e:
        if isinstance(e.message, dict):
            return make_response(jsonify(e.message), e.error_code)
        else:
            return format_response(e.error_code, e.message)
Ejemplo n.º 11
0
def flask_get_by_template(template_id):
    try:
        LOGGER.info(f' Getting devices with template id {template_id}.')
        result = DeviceHandler.get_by_template(request, template_id)
        return make_response(jsonify(result), 200)
    except HTTPRequestError as e:
        LOGGER.error(f' {e.message} - {e.error_code}.')
        if isinstance(e.message, dict):
            return make_response(jsonify(e.message), e.error_code)

        return format_response(e.error_code, e.message)
Ejemplo n.º 12
0
def flask_update_device(device_id):
    try:
        LOGGER.info(f' Updating the device with id {device_id}.')
        results = DeviceHandler.update_device(request, device_id)
        return make_response(jsonify(results), 200)
    except HTTPRequestError as e:
        LOGGER.error(f' {e.message} - {e.error_code}.')
        if isinstance(e.message, dict):
            return make_response(jsonify(e.message), e.error_code)

        return format_response(e.error_code, e.message)
Ejemplo n.º 13
0
def flask_internal_get_device(device_id):
    try:
        result = DeviceHandler.get_device(request, device_id, True)
        LOGGER.info(f' Get known device with id: {device_id}.')
        return make_response(jsonify(result), 200)
    except HTTPRequestError as e:
        LOGGER.error(f' {e.message} - {e.error_code}.')
        if isinstance(e.message, dict):
            return make_response(jsonify(e.message), e.error_code)

        return format_response(e.error_code, e.message)
Ejemplo n.º 14
0
def flask_update_template(template_id):
    try:
        result = TemplateHandler.update_template(request, template_id)
        return make_response(jsonify(result), 200)
    except ValidationError as e:
        results = {'message': 'failed to parse attr', 'errors': e}
        return make_response(jsonify(results), 500)
    except HTTPRequestError as error:
        if isinstance(error.message, dict):
            return make_response(jsonify(error.message), error.error_code)
        else:
            return format_response(error.error_code, error.message)
Ejemplo n.º 15
0
def flask_remove_template_from_device(device_id, template_id):
    try:
        LOGGER.info(f' Removing template with id {template_id} in the device {device_id}.')
        result = DeviceHandler.remove_template_from_device(
            request, device_id, template_id)
        return make_response(jsonify(result), 200)
    except HTTPRequestError as e:
        LOGGER.error(f' {e.message} - {e.error_code}.')
        if isinstance(e.message, dict):
            return make_response(jsonify(e.message), e.error_code)

        return format_response(e.error_code, e.message)
Ejemplo n.º 16
0
def flask_configure_device(device_id):
    """
    Send actuation commands to the device
    """
    try:
        result = DeviceHandler.configure_device(request, device_id)
        return make_response(jsonify(result), 200)

    except HTTPRequestError as error:
        if isinstance(error.message, dict):
            return make_response(jsonify(error.message), error.error_code)
        else:
            return format_response(error.error_code, error.message)
Ejemplo n.º 17
0
def flask_remove_template(template_id):
    try:
        result = TemplateHandler.remove_template(request, template_id)
        LOGGER.info(f"Removing template with id: {template_id}")
        return make_response(jsonify(result), 200)
    except ValidationError as e:
        results = {'message': 'failed to parse attr', 'errors': e}
        LOGGER.error(f" {e.message}")
        return make_response(jsonify(results), 500)
    except HTTPRequestError as e:
        LOGGER.error(f" {e.message}")
        if isinstance(e.message, dict):
            return make_response(jsonify(e.message), e.error_code)
        return format_response(e.error_code, e.message)
Ejemplo n.º 18
0
def flask_delete_all_templates():

    try:
        result = TemplateHandler.delete_all_templates(request)

        LOGGER.info(f"deleting all templates")

        return make_response(jsonify(result), 200)

    except HTTPRequestError as error:
        LOGGER.error(f" {error}")
        if isinstance(error.message, dict):
            return make_response(jsonify(error.message), error.error_code)
        return format_response(error.error_code, error.message)
Ejemplo n.º 19
0
def flask_update_log_level():
    try:
        content_type = request.headers.get('Content-Type')
        data_request = request.data

        _, json_payload = parse_payload(content_type, data_request, log_schema)
        LoggerHandler.update_log_level(json_payload['level'])

        return make_response('', 200)

    except HTTPRequestError as error:
        if isinstance(error.message, dict):
            return make_response(jsonify(error.message), error.error_code)
        return format_response(error.error_code, error.message)
Ejemplo n.º 20
0
def flask_remove_device(device_id):
    try:
        # retrieve the authorization token
        token = retrieve_auth_token(request)

        LOGGER.info(f' Removing the device with id {device_id}.')
        results = DeviceHandler.delete_device(device_id, token)
        return make_response(jsonify(results), 200)
    except HTTPRequestError as e:
        LOGGER.error(f' {e.message} - {e.error_code}.')
        if isinstance(e.message, dict):
            return make_response(jsonify(e.message), e.error_code)

        return format_response(e.error_code, e.message)
Ejemplo n.º 21
0
def flask_create_device():
    """
    Creates and configures the given device (in json).

    Check API description for more information about request parameters and
    headers.
    """
    try:
        result = DeviceHandler.create_device(request)
        return make_response(jsonify(result), 200)
    except HTTPRequestError as e:
        if isinstance(e.message, dict):
            return make_response(jsonify(e.message), e.error_code)
        else:
            return format_response(e.error_code, e.message)
Ejemplo n.º 22
0
def flask_configure_device(device_id):
    """
    Send actuation commands to the device
    """
    try:
        LOGGER.info(f' Actuating in the device with id {device_id}.')
        result = DeviceHandler.configure_device(request, device_id)
        return make_response(jsonify(result), 200)

    except HTTPRequestError as error:
        LOGGER.error(f' {e.message} - {e.error_code}.')
        if isinstance(error.message, dict):
            return make_response(jsonify(error.message), error.error_code)
        
        return format_response(error.error_code, error.message)
Ejemplo n.º 23
0
def flask_internal_get_devices():
    """
    Fetches known devices, potentially limited by a given value. Ordering might
    be user-configurable too.

    Check API description for more information about request parameters and
    headers.
    """
    try:
        result = DeviceHandler.get_devices(request, True)
        return make_response(jsonify(result), 200)
    except HTTPRequestError as e:
        if isinstance(e.message, dict):
            return make_response(jsonify(e.message), e.error_code)
        else:
            return format_response(e.error_code, e.message)
Ejemplo n.º 24
0
def flask_delete_all_device():
    """
    Creates and configures the given device (in json).

    Check API description for more information about request parameters and
    headers.
    """
    try:
        result = DeviceHandler.delete_all_devices(request)

        LOGGER.info('Deleting all devices.')
        return make_response(jsonify(result), 200)
    except HTTPRequestError as e:
        LOGGER.error(f' {e.message} - {e.error_code}.')

        return format_response(e.error_code, e.message)
Ejemplo n.º 25
0
def flask_update_template(template_id):
    try:
        result = TemplateHandler.update_template(request, template_id)
        LOGGER.info(f"Updating template with id: {template_id}")
        return make_response(jsonify(result), 200)
    except ValidationError as errors:
        results = {
            'message': 'failed to parse attr',
            'errors': errors.messages
        }
        LOGGER.error(f' Error in load attrs {errors.messages}')
        return make_response(jsonify(results), 400)
    except HTTPRequestError as error:
        LOGGER.error(f" {error.message}")
        if isinstance(error.message, dict):
            return make_response(jsonify(error.message), error.error_code)
        return format_response(error.error_code, error.message)
Ejemplo n.º 26
0
def flask_create_template():
    try:
        result = TemplateHandler.create_template(request)

        LOGGER.info(f"Creating a new template")

        return make_response(jsonify(result), 200)

    except ValidationError as e:
        results = {'message': 'failed to parse attr', 'errors': e}
        LOGGER.error(f" {e}")
        return make_response(jsonify(results), 400)
    except HTTPRequestError as error:
        LOGGER.error(f" {error}")
        if isinstance(error.message, dict):
            return make_response(jsonify(error.message), error.error_code)
        return format_response(error.error_code, error.message)
Ejemplo n.º 27
0
def flask_add_template_to_device(device_id, template_id):
    try:
        # retrieve the authorization token
        token = retrieve_auth_token(request)

        LOGGER.info(
            f' Adding template with id {template_id} in the device {device_id}.'
        )
        result = DeviceHandler.add_template_to_device(token, device_id,
                                                      template_id)
        return make_response(jsonify(result), 200)
    except HTTPRequestError as e:
        LOGGER.error(f' {e.message} - {e.error_code}.')
        if isinstance(e.message, dict):
            return make_response(jsonify(e.message), e.error_code)

        return format_response(e.error_code, e.message)
Ejemplo n.º 28
0
def flask_get_template(template_id):
    try:
        # retrieve the authorization token
        token = retrieve_auth_token(request)

        params = {'attrs_format': request.args.get('attr_format', 'both')}

        result = TemplateHandler.get_template(params, template_id, token)
        LOGGER.info(f"Getting template with id: {template_id}")
        return make_response(jsonify(result), 200)
    except ValidationError as e:
        results = {'message': 'failed to parse attr', 'errors': e}
        LOGGER.error(f" {e}")
        return make_response(jsonify(results), 500)
    except HTTPRequestError as e:
        LOGGER.error(f" {e}")
        if isinstance(e.message, dict):
            return make_response(jsonify(e.message), e.error_code)
        return format_response(e.error_code, e.message)
Ejemplo n.º 29
0
def flask_get_templates():
    try:
        result = TemplateHandler.get_templates(request)

        for templates in result.get('templates'):
            LOGGER.info(f" Getting template with id {templates.get('id')}")

        return make_response(jsonify(result), 200)

    except ValidationError as e:
        results = {'message': 'failed to parse attr', 'errors': e}
        LOGGER.error(f" {e}")
        return make_response(jsonify(results), 500)

    except HTTPRequestError as e:
        LOGGER.error(f" {e}")
        if isinstance(e.message, dict):
            return make_response(jsonify(e.message), e.error_code)
        return format_response(e.error_code, e.message)
Ejemplo n.º 30
0
def flask_create_device():
    """
    Creates and configures the given device (in json).

    Check API description for more information about request parameters and
    headers.
    """
    try:
        result = DeviceHandler.create_device(request)
        devices = result.get('devices')
        deviceId = devices[0].get('id')
        LOGGER.info(f' Creating a new device with id {deviceId}.')
        return make_response(jsonify(result), 200)
    except HTTPRequestError as e:
        LOGGER.error(f' {e.message} - {e.error_code}.')
        if isinstance(e.message, dict):
            return make_response(jsonify(e.message), e.error_code)
        
        return format_response(e.error_code, e.message)