示例#1
0
def get_employee(employee_id):
    """Get the employee details against the given employee id.
    :param employee_id: int - Unique identification of employee.
    :return: Employee details against the given employee id.
    :raises: sqlalchemy exceptions.
    """
    try:
        result_set = session.query(
            Employee, department.Department.name
        ).join(
            department.Department,
            Employee.department_id == department.Department.department_id
        ).filter(
            Employee.employee_id == employee_id
        ).one()
        result = {
            'employee': {
                'address': result_set[0].address,
                'date_of_joining': str(result_set[0].date_of_joining),
                'department': result_set[1],
                'employee_id': result_set[0].employee_id,
                'gender': result_set[0].gender,
                'name': result_set[0].name,
                'salary': float(str("%0.2f" % result_set[0].salary))
            }
        }
        return response.Response(result)
    except NoResultFound:
        return response.create_not_found_response(
            constants.ERROR_MESSAGE_NOT_FOUND.format(
                title='employee id', id=employee_id))
    except (exc.SQLAlchemyError, exc.DBAPIError):
        return response.create_fatal_response(
            constants.ERROR_MESSAGE_INTERNAL_ERROR)
示例#2
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())
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
示例#4
0
def put_employee(employee_id, payload):
    """Update the employee details against the given employee id.
    :param employee_id: int - Unique identification of employee.
    :param payload: json - Employee details.
    :return: Success message on update of employee details.
    :raises: sqlalchemy exceptions.
    """
    try:
        employee = {
            'address': payload.get('address'),
            'date_of_joining': payload.get('date_of_joining'),
            'department_id': payload.get('department_id'),
            'gender': payload.get('gender'),
            'name': payload.get('name'),
            'salary': payload.get('salary')
        }
        affected_row = session.query(Employee).filter(
            Employee.employee_id == employee_id).update(employee)
        if not affected_row:
            raise NoResultFound
        session.commit()
        return response.Response(message=constants.UPDATE_MESSAGE.format(
            module='Employee', title='employee id', id=employee_id))
    except NoResultFound:
        return response.create_not_found_response(
            constants.ERROR_MESSAGE_NOT_FOUND.format(
                title='employee id', id=employee_id))
    except(exc.SQLAlchemyError, exc.DBAPIError):
        return response.create_fatal_response(
            constants.ERROR_MESSAGE_INTERNAL_ERROR)
示例#5
0
def delete_book(book_id):
    with mysql_connector.db_session() as session:
        existing_book_result = session.query(Book).get(book_id)
        if not existing_book_result:
            return response.create_not_found_response()
        session.delete(existing_book_result)
        session.commit()
    return response.Response(message='Successfully deleted book: {}'.format(
        existing_book_result.BOOK_TITLE))
示例#6
0
def test_get_books_fail(client, headers):
    """Test get books when none found."""
    (flexmock(book_model).should_receive('get_books').and_return(
        response.create_not_found_response()).once())

    result = client.get('/books', headers=headers)
    result_message = json.loads(result.data.decode())

    assert result.status_code == 404
    assert result_message.get('code') == 'not_found_error'
示例#7
0
def update_book(book_id, book_data):
    with mysql_connector.db_session() as session:
        existing_book = session.query(Book).get(book_id)
        if not existing_book:
            return response.create_not_found_response()
        for book_prop in book_data:
            setattr(existing_book, book_prop, book_data.get(book_prop))
        session.merge(existing_book)
        updated_book = existing_book.to_dict()
    return response.Response(updated_book)
def test_get_node_not_found(test_node_id, mocker):
    """Test get node data with not found error."""
    mocker.patch.object(
        crud_logic,
        'read_nodeid',
        return_value=response.create_not_found_response('No Node\
                                             exists for given nodeid'))

    with application.app.test_request_context():
        handler_response = handlers.read_a_node(test_node_id)
        assert handler_response.status_code == 404
        crud_logic.read_nodeid.assert_called_with(test_node_id)
def get_all_users(user_id):

    with db_session() as sesion:
        result = sesion.query(VectorapiUsers) \
            .filter(VectorapiUsers.user_id == user_id)\
            .all()

        if not result:
            return response.create_not_found_response('No user found.')

        dict_result = [user.to_dict() for user in result]

        return response.Response(message=dict_result)
def update_users(user_id, data):

    with db_session() as session:
        existing_user = session.query(VectorapiUsers).get(user_id)

        if not existing_user:
            return response.create_not_found_response('No user found.')

        existing_user.name = data.get('name')
        existing_user.api_key = data.get('api_key')
        existing_user.api_secret = data.get('api_secret')
        session.merge(existing_user)
        session.flush()
        return response.Response(message=existing_user.to_dict())
示例#11
0
def get_all_product():
    """Get all the products.
    Returns:
        response.Response: containing dict of product or error.
    """

    with mysql.db_session() as session:
        product = session.query(Product).all()

        if not product:
            return response.create_not_found_response()

        response_data = [each.to_dict() for each in product]

    return response.Response(message=response_data)
示例#12
0
def test_get_product_live_time_detail_for_not_found(monkeypatch):
    """Test for get product live time with product_id not found."""
    product_id = 1
    expected_response = error.ERROR_MESSAGE_PRODUCT_NOT_FOUND.format(
        product_id)
    monkeypatch.setattr(
        product_live_time, 'get_product_live_time_details',
        MagicMock(return_value=response.create_not_found_response(
            message=expected_response)))

    request_url = '/product/{product_id}'.format(product_id=product_id)

    result = app.test_client().get(request_url)

    assert result.status_code == http_status.NOT_FOUND
示例#13
0
def test_update_book_fail(client, headers):
    """Test update_book when book not found."""
    mock_updated_book = {'title': 'new title'}

    (flexmock(book_model).should_receive('update_book').with_args(
        1, mock_updated_book).and_return(
            response.create_not_found_response()).once())

    result = client.put('book/1',
                        data=json.dumps(mock_updated_book),
                        headers=headers)
    result_message = json.loads(result.data.decode())

    assert result.status_code == 404
    assert result_message.get('code') == 'not_found_error'
示例#14
0
def get_nodes_all():
    """Get all nodes.

    Args:

    Returns:
        response.Response: All the nodes from the table
    """
    with mysql.db_session() as session:
        result_set = session.query(Node).all()

        if not result_set:
            return response.create_not_found_response('No nodes found')

        total_records = [r.to_dict() for r in result_set]
        return response.Response(message=total_records)
示例#15
0
def get_product_by_id(product_id):
    """Get product information by product id.

    Args:
        product_id (int): unique identifier for the product (product_id).
    Returns:
        response.Response: containing dict of product or error.
    """

    with mysql.db_session() as session:
        product = session.query(Product).get(product_id)

        if not product:
            return response.create_not_found_response(
                'product id:{} not found.'.format(product_id))

        return response.Response(message=product.to_dict())
def get_product_live_time_details(product_id):
    """Get all information of product live time for given product id.

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

    Return:
        response: message containing data upon successful query.
            error Response message otherwise.
    """
    with sql.db_session() as session:
        product_live_time = session.query(ProductLiveTime).get(product_id)
        if not product_live_time:
            return response.create_not_found_response(
                error.ERROR_MESSAGE_PRODUCT_NOT_FOUND.format(product_id))

        return response.Response(message=product_live_time.to_dict())
示例#17
0
def get_node_for(nodeid):
    """Get node for passed node id.

    Args:
        nodeid (int): the id of the node.

    Returns:
        response.Response: the node data for the said nodeid.
    """
    with mysql.db_session() as session:
        result_set = session.query(Node).get(nodeid)
        if result_set:
            response_message = response.Response(message=result_set.to_dict())
        else:
            response_message = response.create_not_found_response(
                message='No Node exists for given nodeid')

    return response_message
示例#18
0
def delete_product_by_id(data):
    """Delete product with data provided.
    Args:
        product_id (int): primary key product_id.
        data (dict): additional translations for fields.
    Returns:
        Response: A Response obj with message
    """

    with mysql.db_session() as session:
        saved_artist = session.query(Product).get(data)

        if not saved_artist:
            return response.create_not_found_response(
                'product id:{} not found.'.format(data))

        product = saved_artist.to_dict()
        session.delete(saved_artist)
        return response.Response(
            message='{} successfully deleted.'.format(product))
示例#19
0
def delete_node(nodeid):
    """Delete node for passed node id.

    Args:
        nodeid (int): the id of the node.

    Returns:
        response.Response: the node data for the said nodeid.
    """
    with mysql.db_session() as session:
        result_set = session.query(Node).get(nodeid)
        if result_set:
            session.delete(result_set)
            response_message = response.Response(
                message='Node deleted successfully')
        else:
            response_message = response.create_not_found_response(
                'No node found to delete')

    return response_message
def delete_product_live_time_details(product_id):
    """Delete product live time details by product id.

    Args:
        product_id (int): Product id to delete product live time details.

    Returns:
        response.Response: Response containing delete success message or error
        response message.
    """
    with sql.db_session() as session:
        affected_row_count = session.query(ProductLiveTime).filter(
            ProductLiveTime.product_id == product_id).delete()

        if not affected_row_count:
            return response.create_not_found_response(
                error.ERROR_MESSAGE_PRODUCT_NOT_FOUND.format(product_id))

        return response.Response(
            message=success.DELETE_SUCCESS_MESSAGE_TIMED_RELEASE)
示例#21
0
def delete_department(department_id):
    """Delete the department details against the given department id.
    :param department_id: int - Unique identification of department.
    :return: Success message on delete department details.
    :raises: sqlalchemy exceptions.
    """
    try:
        result_set = session.query(Department). \
            filter(Department.department_id == department_id).one()
        session.delete(result_set)
        session.commit()
        return response.Response(message=constants.DELETE_MESSAGE.format(
            module='Department', title='department id', id=department_id))
    except NoResultFound:
        return response.create_not_found_response(
            constants.ERROR_MESSAGE_NOT_FOUND.format(title='department id',
                                                     id=department_id))
    except (exc.SQLAlchemyError, exc.DBAPIError):
        return response.create_fatal_response(
            constants.ERROR_MESSAGE_INTERNAL_ERROR)
def update_product_live_time_details(product_id, data):
    """Update information of product live time for given product id.

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

    Return:
        response.Response: Response message upon successful update.
        error Response message otherwise.
    """
    with sql.db_session() as session:
        affected_row_count = session.query(ProductLiveTime).filter(
            ProductLiveTime.product_id == product_id).update(data)

        if not affected_row_count:
            return response.create_not_found_response(
                error.ERROR_MESSAGE_PRODUCT_NOT_FOUND.format(product_id))

        return response.Response(
            message=success.UPDATE_SUCCESS_MESSAGE.format(product_id))
示例#23
0
def put_department(department_id, payload):
    """Update the department details against the given department id.
    :param department_id: int - Unique identification of department.
    :param payload: json - Department details.
    :return: Success message on update of department details.
    :raises: sqlalchemy exceptions.
    """
    try:
        department = {'name': payload.get('name')}
        affected_row = session.query(Department).filter(
            Department.department_id == department_id).update(department)
        if not affected_row:
            raise NoResultFound
        session.commit()
        return response.Response(message=constants.UPDATE_MESSAGE.format(
            module='Department', title='department id', id=department_id))
    except NoResultFound:
        return response.create_not_found_response(
            constants.ERROR_MESSAGE_NOT_FOUND.format(title='department id',
                                                     id=department_id))
    except (exc.SQLAlchemyError, exc.DBAPIError):
        return response.create_fatal_response(
            constants.ERROR_MESSAGE_INTERNAL_ERROR)
示例#24
0
def get_department(department_id):
    """Get the department details against the given department id.
    :param department_id: int - Unique identification of department.
    :return: Department details against the given department id.
    :raises: sqlalchemy exceptions.
    """
    try:
        result_set = session.query(Department). \
            filter(Department.department_id == department_id).one()
        result = {
            'department': {
                'department_id': result_set.department_id,
                'name': result_set.name
            }
        }
        return response.Response(result)
    except NoResultFound:
        return response.create_not_found_response(
            constants.ERROR_MESSAGE_NOT_FOUND.format(title='department id',
                                                     id=department_id))
    except (exc.SQLAlchemyError, exc.DBAPIError):
        return response.create_fatal_response(
            constants.ERROR_MESSAGE_INTERNAL_ERROR)