def __init__(self, **kwargs): super().__init__(**kwargs) self._entity_manager = BusinessEntityManager() self._logger = logging.getLogger(__name__) self._validator = JsonSchemaValidator() self._schema_loader = SchemaLoader() self._permission_classes = (IsAuthenticated, )
class DeleteBusinessEntityController(APIView): _entity_manager = None def __init__(self, **kwargs): super().__init__(**kwargs) self._entity_manager = BusinessEntityManager() self._logger = logging.getLogger(__name__) self._validator = JsonSchemaValidator() self._permission_classes = (IsAuthenticated,) def post(self, request: Request, business_entity: str) -> Response: if not self.has_delete_permission(business_entity, request): return ControllerUtils.unauthorized_response() body = ControllerUtils.extract_body(request) key = body[Constants.KEY] if not self._validator.business_entity_exist(business_entity): return ControllerUtils.business_entity_not_exist_response(business_entity) if Constants.VERSION not in body: return self._delete_all_versions(business_entity, key) return self._delete_from_version(body, business_entity, key) def _delete_all_versions(self, business_entity, key) -> Response: number_of_deleted_objects = self._entity_manager.delete_by_key( business_entity, key ) message = Constants.DELETE_ALL_VERSIONS_MESSAGE if number_of_deleted_objects > 0 \ else Constants.DELETE_ALL_VERSIONS_MESSAGE_NOT_FOUND return ControllerUtils.custom_response( message.format(key), status.HTTP_200_OK ) def _delete_from_version(self, body, business_entity, key) -> Response: version = body[Constants.VERSION] if not self._validator.version_exist(version, business_entity): return ControllerUtils.custom_response( Constants.VERSION_NOT_EXIST.format(version), status.HTTP_400_BAD_REQUEST ) number_of_deleted_objects = self._entity_manager.delete(business_entity, key, version) message = Constants.DELETE_FROM_VERSION_MESSAGE if number_of_deleted_objects > 0 \ else Constants.DELETE_FROM_VERSION_MESSAGE_NOT_FOUND return ControllerUtils.custom_response( message.format(key, version), status.HTTP_200_OK ) def has_delete_permission(self, business_entity: str, request: Request) -> bool: delete_permission = ControllerUtils.get_permission_string(Constants.DELETE, business_entity) return Permission.objects\ .filter(user=request.user)\ .filter(codename=delete_permission)\ .exists()
class Command(BaseCommand): help = 'publish all data from a business entity to the business entity channel/topic' def __init__(self, **kwargs): super().__init__(**kwargs) self._entity_manager = BusinessEntityManager() self._logger = logging.getLogger(__name__) self._chunk_size = settings.DEFAULT_CHUNK_SIZE self._message_service = MessagePublisher() def add_arguments(self, parser): parser.add_argument(Constants.BUSINESS_ENTITY, type=str) parser.add_argument(Constants.CHUNK_SIZE, type=int, nargs='?', default=settings.DEFAULT_CHUNK_SIZE) def handle(self, *args, **kwargs): self._chunk_size = kwargs[Constants.CHUNK_SIZE] business_entity = kwargs[Constants.BUSINESS_ENTITY] queryset = self._entity_manager.find_all(business_entity) for business_entity in queryset.iterator(chunk_size=self._chunk_size): self._message_service.send_entity_update_message(business_entity) self._message_service.shutdown()
class SaveBusinessEntityController(APIView): _entity_manager = None def __init__(self, **kwargs): super().__init__(**kwargs) self._entity_manager = BusinessEntityManager() self._logger = logging.getLogger(__name__) self._validator = JsonSchemaValidator() self._schema_loader = SchemaLoader() self._permission_classes = (IsAuthenticated, ) def post(self, request: Request, business_entity: str) -> Response: if not self._validator.business_entity_exist(business_entity): return ControllerUtils.business_entity_not_exist_response( business_entity) if not self.has_save_permission(business_entity, request): return ControllerUtils.unauthorized_response() body = ControllerUtils.extract_body(request) if Constants.VERSION not in body: return ControllerUtils.custom_response(Constants.VERSION_MISSING, status.HTTP_400_BAD_REQUEST) version = body[Constants.VERSION] key = body[Constants.KEY] payload = body[Constants.PAYLOAD] error_messages = self._validator.validate_schema( payload, business_entity, version) if error_messages: return ControllerUtils.custom_response(error_messages, status.HTTP_400_BAD_REQUEST) created = self._entity_manager.update_or_create( business_entity, key, version, request.user, payload) return self._create_response(created, key, version) def _create_response(self, created, key, version): if created: return ControllerUtils.custom_response( Constants.SAVE_MESSAGE.format(key, version), status.HTTP_201_CREATED) return ControllerUtils.custom_response( Constants.UPDATE_MESSAGE.format(key, version), status.HTTP_200_OK) def has_save_permission(self, business_entity: str, request: Request) -> bool: if type(request.user) is AnonymousUser: return False add_permission = ControllerUtils.get_permission_string( Constants.ADD, business_entity) change_permission = ControllerUtils.get_permission_string( Constants.CHANGE, business_entity) return Permission.objects \ .filter(user=request.user) \ .filter(codename__in=[add_permission, change_permission]) \ .count() == 2
class ReadOnlyAdmin(admin.ModelAdmin): fields = ('key', 'version', 'data_prettified', 'created', 'modified') list_display = ['key', 'version'] search_fields = ['key', 'version'] _entity_manager = BusinessEntityManager() def has_add_permission(self, request, obj=None): return False def has_change_permission(self, request, obj=None): return False def has_delete_permission(self, request, obj=None): return settings.WAYNE_ADMIN.get('DELETE_ENABLED') def delete_model(self, request, entity): self._entity_manager.delete_by_instance(entity) def delete_queryset(self, request, queryset): self._entity_manager.delete_by_queryset(queryset) def data_prettified(self, model): json_data = json.dumps(model.data, sort_keys=True, indent=2) return mark_safe('<pre id="json-renderer" class="json-document">' + json_data + '</pre>') data_prettified.short_description = 'data' class Media: js = (settings.JSON_VIEWER.get('JS_URL'), settings.WAYNE_ADMIN.get('JS_URL')) css = { 'all': (settings.JSON_VIEWER.get('CSS_URL'), settings.WAYNE_ADMIN.get('CSS_URL')) }
def setUp(self): self._entity_manager = BusinessEntityManager()
class BusinessEntityManagerTestCase(TestCase): def setUp(self): self._entity_manager = BusinessEntityManager() @mock.patch.object(MessagePublisher, 'send_entity_update_message') @mock.patch.object(ManagerTestEntity, 'objects') @mock.patch.object(BusinessEntityUtils, 'get_entity_class', return_value=ManagerTestEntity) def test_create(self, mock_entity_utils, mock_objects, mock_send_entity_update_message): mock_objects.update_or_create.return_value = (entity, True) created = self._entity_manager.update_or_create( entity_name, key, version, test_user, data) self.assertTrue(created) mock_objects.update_or_create.assert_called_once() mock_send_entity_update_message.assert_called_once_with(entity) @mock.patch.object(MessagePublisher, 'send_entity_update_message') @mock.patch.object(ManagerTestEntity, 'objects') @mock.patch.object(BusinessEntityUtils, 'get_entity_class', return_value=ManagerTestEntity) def test_update(self, mock_entity_utils, mock_objects, mock_send_entity_update_message): # create entity, should send one message mock_objects.update_or_create.return_value = (entity, False) created = self._entity_manager.update_or_create( entity_name, key, version, test_user, data) self.assertFalse(created) mock_objects.update_or_create.assert_called_once() mock_send_entity_update_message.assert_called_once_with(entity) @mock.patch.object(MessagePublisher, 'send_entity_delete_message') @mock.patch.object(QuerySet, 'delete') @mock.patch.object(QuerySet, 'all') @mock.patch.object(BusinessEntityUtils, 'get_entity_class', return_value=ManagerTestEntity) def test_delete(self, mock_entity_utils, mock_queryset_all, mock_queryset_delete, mock_send_entity_delete_message): mock_queryset_all.return_value = [entity] mock_queryset_delete.return_value = (1, {}) delete_count = self._entity_manager.delete(entity_name, key, version) self.assertEqual(1, delete_count) mock_send_entity_delete_message.assert_called_once_with(entity) @mock.patch.object(MessagePublisher, 'send_entity_delete_message') @mock.patch.object(QuerySet, 'delete') @mock.patch.object(QuerySet, 'all') @mock.patch.object(BusinessEntityUtils, 'get_entity_class', return_value=ManagerTestEntity) def test_delete_by_key(self, mock_entity_utils, mock_queryset_all, mock_queryset_delete, mock_send_entity_delete_message): mock_queryset_all.return_value = [entity, entity] mock_queryset_delete.return_value = (2, {}) delete_count = self._entity_manager.delete_by_key(entity_name, key) self.assertEqual(2, delete_count) mock_send_entity_delete_message.assert_has_calls( [call(entity), call(entity)])
def __init__(self, **kwargs): super().__init__(**kwargs) self._entity_manager = BusinessEntityManager() self._logger = logging.getLogger(__name__) self._chunk_size = settings.DEFAULT_CHUNK_SIZE self._message_service = MessagePublisher()