def update_vendor_by_id(data): """update vendor by its id. Note: This method will update name, company of vendor by id. Args: vendor_id (int), name(varchar), company(varchar) Returns: response.Response: update message. """ if data == {}: return response.Response('Invalid data.') with mysql.db_session() as session: saved_vendor = session.query(Vendor) \ .filter_by(vendor_id=data['vendor_id'])\ .one_or_none() if not saved_vendor: return response.Response('{} record id not found.'.format( data['vendor_id'])) else: saved_vendor.name = data['name'] if data['company'] is not None: saved_vendor.company = data['company'] session.merge(saved_vendor) return response.Response('data updated successfully')
def update_test_data(data): """Update test by its id. Note: This method will update name of test by id. Args: data contains: id (int), name(varchar) Returns: response.Response: update message. """ if data == {}: return response.Response('Invalid data.') with mysql.db_session() as session: update_test = session.query(Test) \ .filter_by(test_id=data['id']) \ .one_or_none() if not update_test: return response.Response('{} test id not found.'.format( data['id'])) else: update_test.name = data['name'] session.merge(update_test) return response.Response(message=update_test.to_dict())
def say_hello(name=None): """Logic handlers. Args: name (str): the name to display alongside the Hello. Returns: Response: the hello message. """ if not name or isinstance(name, str) and not name.strip(): return response.Response('Hello') return response.Response('Hello {}!'.format(name))
def get_all_tests(): """Get all test list. Returns: list of tests. """ with mysql.db_session() as session: result_set = session.query(Test).all() if not result_set: return response.Response('test data not available.') total_records = [r.to_dict() for r in result_set] return response.Response(message=total_records)
def test_response_creation_with_status(): """Test the response creation with a defined status. Within the 200's, the response is considered valid. Above it's invalid. """ for status in range(200, 300): resp = response.Response(status=status) assert resp assert resp.status == status for status in range(300, 500): resp = response.Response(status=status) assert not resp assert resp.status == status
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)
def health_check(): """Health check for application Return: response.Response, a health message """ return flaskify(response.Response('all is well that begins well'))
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 get_books(): with mysql_connector.db_session() as session: books = session.query(Book).all() books_list = [] for book in books: books_list.append(book.to_dict()) return response.Response(message=books_list)
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)
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)
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)
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!!!')
def get_all_language(): """Get all languages. """ with mysql.db_session() as session: ItunesLanguage = session.query(ItunesLanguages).all() returnlist = [each.to_dict() for each in ItunesLanguage] return response.Response(message=returnlist)
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 test_flaskify_string_response(): """Test flaskifying a response. """ resp = flask.flaskify(response.Response(message='value1')) assert resp.data == b'value1' assert resp.mimetype == 'text/plain' assert resp.status_code == 200
def test_flaskify_list_response(): """Test flaskifying a response. """ resp = flask.flaskify(response.Response(message=['value1', 'value2'])) assert resp.data == b'["value1", "value2"]' assert resp.mimetype == 'application/json' assert resp.status_code == 200
def test_flaskify_dict_response(): """Test flaskifying a response. """ resp = flask.flaskify(response.Response(message=dict(key='value'))) assert resp.data == b'{"key": "value"}' assert resp.mimetype == 'application/json' assert resp.status_code == 200
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 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()
def test_response_creation(): """Test the default response creation. """ resp = response.Response() assert not resp.message assert not resp.errors assert resp assert resp.status == 200
def test_response_creation_with_message(): """Test the creation of a response with a message. """ message = 'something' resp = response.Response(message=message) assert resp assert resp.message == message assert resp.status == 200
def test_get_product_live_time_detail_for_db_failure(mocker): """Test db failure response.""" mocker.patch.object(product_live_time, 'get_product_live_time_details', return_value=response.Response(status=500)) result = app.test_client().get('/product/1') assert result.status_code == http_status.INTERNAL_ERROR
def test_get_node_by_nodeid_success(test_node_id, mocker): """Test response contents upon success.""" mocker.patch.object( crudmodel, 'get_node_for', return_value=response.Response(message=test_node_id)) result = crud_logic.read_nodeid(test_node_id) assert result assert result.message == test_node_id
def test_delete_the_node_success(test_node_id, mocker): """Test response contents upon success.""" mocker.patch.object( crudmodel, 'delete_node', return_value=response.Response('Node deleted successfully')) result = crud_logic.remove_nodeid(test_node_id) assert result assert result.message == 'Node deleted successfully'
def test_create_new_node_success(test_create_single_node, mocker): """Test response contents upon success.""" mocker.patch.object( crudmodel, 'create_node', return_value=response.Response(message=test_create_single_node)) result = crud_logic.add_node(test_create_single_node) assert result assert result.message == test_create_single_node
def test_delete_book(client, headers): """Test delete a book.""" delete_message = 'Successfully deleted book: test title' (flexmock(book_model).should_receive('delete_book').with_args( 3).and_return(response.Response(message=delete_message)).once()) result = client.delete('/book/3', headers=headers) assert result.status_code == 200
def add_test_data(data): """Add test data. Args: data contains: name(varchar) Returns: saved records. """ # validate data sent are valid or non empty (this is optional case). if not data: return response.Response('data is invalid.') with mysql.db_session() as session: new_test = Test(name=data) session.add(new_test) return response.Response(new_test.to_dict())
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))
def insert_user(data): with mysql.db_session() as session: new_user = VectorapiUsers() new_user.name = data.get('user_name', 'demo') new_user.api_key = data.get('api_key') new_user.api_secret = data.get('api_secret', 'secret') session.add(new_user) session.flush() # only if you need the new id return response.Response(message=new_user.to_dict())