Example #1
0
def update_language(data):
    """Update language information .
    Args:
        id (int): unique identifier for the language (language_id).
        data (str): dictionary record contain language_name and language_code
    Returns:
        response.Response: message or error.
    """
    if not isinstance(data, dict) or not data:
        return response.create_error_response(
            error.ERROR_CODE_NOT_FOUND, 'Invalid data sent for save language.')

    with mysql.db_session() as session:
        update_language = session.query(ItunesLanguages) \
            .get(data.get('language_id'))
        if not update_language:
            return response.create_error_response(
                error.ERROR_CODE_NOT_FOUND,
                '{} record id not found.'.format(data['language_id']))
        else:
            update_language.language = data.get('language_name')
            update_language.language_code = data.get('language_code')
            session.merge(update_language)

    return response.Response(message='Data updated!!!')
Example #2
0
def put_employee(employee_id, payload):
    """Update the employee details against the given employee id.
    :param employee_id: str - Unique identification of employee.
    :param payload: json - Request body.
    :return: Success message on update of employee details.
    """
    if not validator.is_number(employee_id):
        return response.create_error_response(
            code=constants.ERROR_CODE_BAD_REQUEST,
            message=constants.ERROR_MESSAGE_BAD_REQUEST.format(
                title='employee id', id=employee_id))
    validate = validator.validate_request(payload, 'PUT', 'employee')
    if validate:
        return response.create_error_response(
            code=constants.ERROR_CODE_BAD_REQUEST, message=validate)
    return employee.put_employee(employee_id, payload)
def update_node(nodeid, paramdict):
    """Update node for passed node.

    Args:
        nodeid: Node ID to update for new column values as passed
        paramdict: Dictionary of column:columnvalue

    Returns:
        response.Response: the node data for the said nodeid.
    """
    if paramdict == {}:
        return response.create_error_response(message='Update data invalid',
                                              code=500)

    with mysql.db_session() as session:
        result_set = session.query(Node).get(nodeid)
        if result_set:
            for colname, colval in paramdict.items():
                setattr(result_set, colname, colval)
            session.merge(result_set)

            response_message = response.Response(message=result_set.to_dict())
        else:
            return response.create_not_found_response(
                'No such node found to update')

    return response_message
def create_product_live_time_details(
        product_id, time_of_day_product, time_zone, store_id=None):
    """Create product live time details.

    Args:
        product_id (int): Unique identification for product.
        time_of_day_product (str): Time to product go live.
        time_zone (str): Time Zone to product go live.
        store_id (int): Unique identification for DMS.
    Returns:
        response.Response: Response dict of inserted product live time
        details or error.
    """
    timed_release_data = {
        'product_id': product_id,
        'time_of_day_product': time_of_day_product,
        'time_zone': time_zone,
        'store_id': store_id
    }

    required_fields = ['product_id', 'time_of_day_product', 'time_zone']
    validation_error = validators.validate_timed_release_dataset(
        timed_release_data, required_fields)

    if validation_error:
        return response.create_error_response(
            code=error.ERROR_CODE_BAD_REQUEST, message=validation_error)

    timed_release_data_to_add = ProductLiveTime(**timed_release_data)
    with sql.db_session() as session:
        session.add(timed_release_data_to_add)
        timed_release_insert_response = {'product': timed_release_data}
        return response.Response(message=timed_release_insert_response)
Example #5
0
    def update(self, source, **data):
        """Update the model from the data passed.
        """

        if not source:
            return response.create_error_response(
                message='The source cannot be empty.')

        data = utils.key_exclude(data, source.keys())
        data = self.validate(data, operation=operations.READ)
        if not data:
            return data

        # Recreate the object - check ancestors.
        current = self.fetch_one(
            **{key: operations.Equal(val)
               for key, val in source.items()})
        if not current:
            return current

        fields = response.Response(
            message=dict(list(source.items()) + list(data.message.items())))

        ancestors = self.ensure_indexes(fields, current.message)
        if not ancestors:
            return ancestors

        return self.table.update(current, fields.message)
Example #6
0
def put_department(department_id, payload):
    """Update the department details against the given department id.
    :param department_id: str - Unique identification of department.
    :param payload: json - Request body.
    :return: Success message on update of department details.
    """
    if not validator.is_number(department_id):
        return response.create_error_response(
            code=constants.ERROR_CODE_BAD_REQUEST,
            message=constants.ERROR_MESSAGE_BAD_REQUEST.format(
                title='department id', id=department_id))
    validate = validator.validate_request(payload, 'PUT', 'department')
    if validate:
        return response.create_error_response(
            code=constants.ERROR_CODE_BAD_REQUEST, message=validate)
    return department.put_department(department_id, payload)
Example #7
0
def update_product_by_id(data):
    """Update product data for the given product_id.
    Args:
        product_id (int): id product.
        data (dict): dict containing product data.
        e.g; {product_id : product_id, product_name : product_name, ..}
        session (object): db session object, to make it transactional.
    Returns:
        response.Response: response object containing dict of product or error.
    """

    if data == {}:
        return response.create_error_response(
            error.ERROR_CODE_NOT_FOUND,
            'Invalid data sent for update product.')

    with mysql.db_session() as session:
        update_product = session.query(Product) \
            .get(data.get('product_id'))
        if not update_product:
            return response.create_not_found_response(
                'product id:{} not found.'.format(data['product_id']))
        else:
            update_product.product_name = data.get('product_name')
            session.merge(update_product)

        return response.Response(message=update_product.to_dict())
Example #8
0
def test_custom_error_response():
    """Test creating a custom error response.
    """

    error_message = 'something'
    resp = response.create_error_response('code', error_message)
    assert resp.errors.get('code') == 'code'
    assert resp.errors.get('message') == error_message
 def authenticate_and_call(*args, **kwargs):
     if not is_authenticated(request.headers):
         return flaskify(
             response.create_error_response(
                 code=constants.ERROR_CODE_UNAUTHORIZED_REQUEST,
                 message=constants.ERROR_MESSAGE_UNAUTHORIZED_ACCESS,
                 status=oto_status.UNAUTHORIZED))
     return func(*args, **kwargs)
Example #10
0
    def ensure_indexes(self, validation_response, current=None):
        """Ensure index unicity.

        One particularity of an index: it should be unique. For example in
        DynamoDb: an index has a hash and a range, combined, they represent the
        key of that specific row – and thus should be unique.

        If an index only has one key, that key on its own should also be
        unique (e.g. user_id).

        Args:
            validation_response (Response): The validation response that
                contains the validated fields.
            current (dict): Operations such as update requires to check against
                the found ancestor and the current row that needs to be
                validated.
        Return:
            Response: The response
        """

        if not validation_response:
            return validation_response

        data = validation_response.message
        errors = {}
        current = current or {}

        for index in self.indexes:
            # Some databases allow to have non unique indexes. In this case,
            # we ignore this index for the check.
            if not index.unique:
                continue

            keys = index.keys

            query = dict()
            for key in keys:
                key_value = data.get(key, current.get(key))
                if not key_value:
                    break
                query.update({key: operations.Equal(key_value)})

            if not query:
                continue

            ancestor = self.fetch_one(**query)
            if ancestor:
                if not current or dict(ancestor.message) != dict(current):
                    errors.update(
                        {key: exceptions.FIELD_ALREADY_USED
                         for key in keys})

        if errors:
            return response.create_error_response(
                consts.ERROR_CODE_DUPLICATE_KEY, errors)

        return response.Response()
Example #11
0
def get_departments(filter_data):
    """Get the departments detail.
    :param filter_data: dict - Data for filter the result.
    :return: Departments detail.
    """
    validate = validator.validate_filter_request(filter_data, 'department')
    if validate:
        return response.create_error_response(
            code=constants.ERROR_CODE_BAD_REQUEST, message=validate)
    return department.get_departments(filter_data)
Example #12
0
def post_employee(payload):
    """Add an employee details.
    :param payload: json - Employee details.
    :return: Employee details added against the given data.
    """
    validate = validator.validate_request(payload, 'POST', 'employee')
    if validate:
        return response.create_error_response(
            code=constants.ERROR_CODE_BAD_REQUEST, message=validate)
    return employee.post_employee(payload)
Example #13
0
def post_department(payload):
    """Add the department details.
    :param payload: json - Department details.
    :return: Department details added against the given data.
    """
    validate = validator.validate_request(payload, 'POST', 'department')
    if validate:
        return response.create_error_response(
            code=constants.ERROR_CODE_BAD_REQUEST, message=validate)
    return department.post_department(payload)
Example #14
0
def get_employees(filter_data):
    """Get the employees detail.
    :param filter_data: dict - Data for filter the result.
    :return: Employees detail.
    """
    validate = validator.validate_filter_request(filter_data, 'employee')
    if validate:
        return response.create_error_response(
            code=constants.ERROR_CODE_BAD_REQUEST, message=validate)
    return employee.get_employees(filter_data)
Example #15
0
def delete_employee(employee_id):
    """Delete the employee details against the given employee id.
    :param employee_id: str - Unique identification of employee.
    :return: Success message on delete employee details.
    """
    if not validator.is_number(employee_id):
        return response.create_error_response(
            code=constants.ERROR_CODE_BAD_REQUEST,
            message=constants.ERROR_MESSAGE_BAD_REQUEST.format(
                title='employee id', id=employee_id))
    return employee.delete_employee(employee_id)
Example #16
0
def get_department(department_id):
    """Get the department details against the given department id.
    :param department_id: str - Unique identification of department.
    :return: Department details against the given department id.
    """
    if not validator.is_number(department_id):
        return response.create_error_response(
            code=constants.ERROR_CODE_BAD_REQUEST,
            message=constants.ERROR_MESSAGE_BAD_REQUEST.format(
                title='department id', id=department_id))
    return department.get_department(department_id)
def update_product_live_time(product_id, data):
    """Update product live time details.

    Args:
        product_id (str): Product id to update Spotify product live time.
        data (dict): Product live time data to be updated.

    Returns:
        response.Response: Response message upon successful update.
         or error Response otherwise.
    """
    if not validators.is_digit_and_non_zero(product_id):
        return response.create_error_response(
            code=error.ERROR_CODE_BAD_REQUEST,
            message=error.ERROR_MESSAGE_INTEGER_NON_NEGATIVE.format(
                product_id))

    validation_error = validators.validate_timed_release_dataset(
        data, data.keys())
    if validation_error:
        return response.create_error_response(
            code=error.ERROR_CODE_BAD_REQUEST, message=validation_error)
    return product_live_time.update_product_live_time_details(product_id, data)
def delete_product_live_time_details(product_id):
    """Delete product live time details by product id.

    Args:
        product_id (str): Product id to delete product live time details.
    Returns:
        response.Response: Response containing delete success message or error
        response message.
    """
    if not validators.is_digit_and_non_zero(product_id):
        return response.create_error_response(
            code=error.ERROR_CODE_BAD_REQUEST,
            message=error.ERROR_MESSAGE_INTEGER_NON_NEGATIVE.format(
                product_id))
    return product_live_time.delete_product_live_time_details(product_id)
Example #19
0
def health_check():
    """Health check handler.
    Checks database connection. 200 if OK, otherwise 503 service unavailable.
    Returns:
        Response: the system status.
    """
    try:
        db.execute("SELECT * FROM label_status")
    except SQLAlchemyError as err:
        print("OS error: {0}".format(err))
        return response.create_error_response(
            code='Internal Server Error',
            message='could not connect to psql',
            status=503)

    return response.Response(message={'status': 'ok'}, status=200)
def get_product_live_time_details(product_id):
    """Check if product id exist in product live table and return it.

    Args:
        product_id (str): Product id to fetch Spotify product live time.

    Return:
        response.Response: product live time details on successful fetch
        or error response.
    """
    if not validators.is_digit_and_non_zero(product_id):
        return response.create_error_response(
            code=error.ERROR_CODE_BAD_REQUEST,
            message=error.ERROR_MESSAGE_INTEGER_NON_NEGATIVE.format(
                product_id))
    return product_live_time.get_product_live_time_details(product_id)
Example #21
0
def get_language_by_id(language_id):
    """Get language information by language id.
    Args:
        language_id (int): unique identifier for the language (language_id).
    Returns:
        response.Response: containing dict of product or error.
    """
    with mysql.db_session() as session:
        ItunesLanguage = session.query(ItunesLanguages).get(language_id)

        if not ItunesLanguage:
            return response.create_error_response(
                error.ERROR_CODE_NOT_FOUND,
                '{} record id not available.'.format(language_id))

        return response.Response(message=ItunesLanguage.to_dict())
Example #22
0
    def validate(self, values, operation):
        """Validate the model.

        Args:
            values (dict): The values to validate.
            operation (int): The different operations
                (correspond to schema operations).
        Return:
            Response.
        """

        data = dict()
        errors = dict()
        success = False
        items = set(values.keys())

        if operation is operations.READ and not values:
            return response.Response()

        if operation is operations.CREATE:
            items = set(self.fields.keys())

        for name in items:
            field = self.fields.get(name)
            if not field:
                continue

            try:
                value = values.get(name)

                if isinstance(value, operations.Base):
                    value = value.validate(field)
                    data[name] = value
                    continue

                data[name] = field.validate(value)

            except exceptions.FieldException as e:
                errors[name] = e.args[0]
                status = False

        if errors:
            return response.create_error_response(consts.ERROR_CODE_VALIDATION,
                                                  errors)

        return response.Response(message=data)
def create_node(paramdict):
    """Update node for passed node id.

    Args:
            paramdict: Dictionary column value pairs to be added as a row
    Returns:
        response.Response: the node
    """
    if paramdict is None or 'name' not in paramdict or 'surname' \
    not in paramdict:
        return response.create_error_response(
            message='Name and surname is mandatory', code=500)

    with mysql.db_session() as session:
        new_node = Node(name=paramdict.get('name'),
                        surname=paramdict.get('surname'))
        session.add(new_node)
        response_message = response.Response(message=paramdict)

    return response_message
Example #24
0
def search_for_books(search_term, search_category):
    """Search for a book."""
    with mysql_connector.db_session() as session:
        if search_category == 'isbn':
            results = session.query(LibraryBook).filter(
                LibraryBook.ISBN.contains(search_term)).limit(20)
        elif search_category == 'title':
            results = session.query(LibraryBook).filter(
                LibraryBook.BOOK_TITLE.contains(search_term)).limit(20)
        elif search_category == 'author':
            results = session.query(LibraryBook).filter(
                LibraryBook.BOOK_AUTHOR.contains(search_term)).limit(20)
        else:
            return response.create_error_response(400,
                                                  'Invalid Search Category')

        results_data = []
        for book in results:
            results_data.append(book.to_dict())

        return response.Response(results_data)
Example #25
0
def create_product_live_time_detail():
    """Save info about product live time detail.

    Returns:
        flask.Response: Response contains dict describing product live time
        details, or validation message.
    """
    valid_request_json = True
    try:
        timed_release_data = request.get_json()
        if not isinstance(timed_release_data, dict):
            valid_request_json = False
    except BadRequest:
        valid_request_json = False

    if not valid_request_json:
        return flaskify(response.create_error_response(
            code=error.ERROR_CODE_BAD_REQUEST,
            message=error.ERROR_MESSAGE_INVALID_REQUEST_BODY))

    return flaskify(product_live_time.create_product_live_time_detail(
        timed_release_data))
Example #26
0
def test_create_product_live_time_detail_failure(description, product_id,
                                                 time_of_day_product,
                                                 time_zone, store_id,
                                                 expected_response,
                                                 monkeypatch):
    """Test for create product live time detail with failure."""
    request_body = {
        'product_id': product_id,
        'time_of_day_product': time_of_day_product,
        'time_zone': time_zone,
        'store_id': store_id
    }

    monkeypatch.setattr(
        product_live_time, 'create_product_live_time_detail',
        MagicMock(return_value=response.create_error_response(
            code=error.ERROR_CODE_BAD_REQUEST, message=expected_response)))

    with app.test_client() as client:
        result = client.post('/product',
                             data=json.dumps(request_body),
                             content_type='application/json')

        assert result.status_code == http_status.BAD_REQUEST