def get_org(self): org_id = self.request.data.get('org_id') if is_uuid(org_id): org = Organization.objects.get(id=org_id) else: org = current_org return org
def get_kwargs_may_be_uuid(value): kwargs = {} if is_uuid(value): kwargs['id'] = value else: kwargs['name'] = value return kwargs
def perform_create(self, serializer): if hasattr(self.request.user, 'terminal'): serializer.validated_data["terminal"] = self.request.user.terminal sid = serializer.validated_data["system_user"] if is_uuid(sid): _system_user = SystemUser.get_system_user_by_id_or_cached(sid) if _system_user: serializer.validated_data["system_user"] = _system_user.name return super().perform_create(serializer)
def perform_create(self, serializer): if hasattr(self.request.user, 'terminal'): serializer.validated_data["terminal"] = self.request.user.terminal sid = serializer.validated_data["system_user"] # guacamole提交的是id if is_uuid(sid): _system_user = get_object_or_404(SystemUser, id=sid) serializer.validated_data["system_user"] = _system_user.name return super().perform_create(serializer)
def get_node(request): node_id = dict_get_any(request.query_params, ['node', 'node_id']) if not node_id: return None if is_uuid(node_id): node = get_object_or_none(Node, id=node_id) else: node = get_object_or_none(Node, key=node_id) return node
def get_query_node(request): region_id = dict_get_any(request.query_params, ['region', 'region_id']) if not region_id: return None, False if is_uuid(region_id): region = get_object_or_none(Region, id=region_id) else: region = get_object_or_none(Region, name=region_id) return region, True
def get_asset_info(obj): asset_id = obj.get('asset') if not asset_id or not is_uuid(asset_id): return {} try: asset = Asset.objects.get(id=str(asset_id)) except ObjectDoesNotExist as e: logger.error(e) return {} if not asset: return {} asset_info = {'id': str(asset.id), 'hostname': asset.hostname} return asset_info
def get_asset_info(obj): asset_id = obj.get('asset') if not asset_id or is_uuid(asset_id): return {} try: asset = Asset.objects.filter(id=str(asset_id)).values_list( 'id', 'hostname') except ObjectDoesNotExist as e: logger.error(e) return {} if not asset: return {} asset_info = {'id': str(asset[0]), 'hostname': asset[1]} return asset_info
def get_instance(cls, id_or_name, default=True): cached = cls.get_instance_from_cache(id_or_name) if cached: return cached if not id_or_name: return cls.default() if default else None elif id_or_name == cls.DEFAULT_ID_NAME: return cls.default() elif id_or_name == cls.ROOT_ID_NAME: return cls.root() try: if is_uuid(id_or_name): org = cls.objects.get(id=id_or_name) else: org = cls.objects.get(name=id_or_name) org.set_to_cache() except cls.DoesNotExist: org = cls.default() if default else None return org
def get_instance(cls, id_or_name, default=False): cached = cls.get_instance_from_cache(id_or_name) if cached: return cached if id_or_name is None: return cls.default() if default else None elif id_or_name in [cls.DEFAULT_ID, cls.DEFAULT_NAME, '']: return cls.default() elif id_or_name in [cls.ROOT_ID, cls.ROOT_NAME]: return cls.root() elif id_or_name in [cls.SYSTEM_ID, cls.SYSTEM_NAME]: return cls.system() try: if is_uuid(id_or_name): org = cls.objects.get(id=id_or_name) else: org = cls.objects.get(name=id_or_name) org.set_to_cache() except cls.DoesNotExist: org = cls.default() if default else None return org
def form_valid(self, form): f = form.cleaned_data['file'] det_result = chardet.detect(f.read()) f.seek(0) # reset file seek index file_data = f.read().decode(det_result['encoding']).strip(codecs.BOM_UTF8.decode()) csv_file = StringIO(file_data) reader = csv.reader(csv_file) csv_data = [row for row in reader] fields = [ field for field in Asset._meta.fields if field.name not in [ 'date_created' ] ] header_ = csv_data[0] mapping_reverse = {field.verbose_name: field.name for field in fields} attr = [mapping_reverse.get(n, None) for n in header_] if None in attr: data = {'valid': False, 'msg': 'Must be same format as ' 'template or export file'} return self.render_json_response(data) created, updated, failed = [], [], [] assets = [] for row in csv_data[1:]: if set(row) == {''}: continue asset_dict = dict(zip(attr, row)) id_ = asset_dict.pop('id', 0) for k, v in asset_dict.items(): if k == 'is_active': v = True if v in ['TRUE', 1, 'true'] else False elif k == 'admin_user': v = get_object_or_none(AdminUser, name=v) elif k in ['port', 'cpu_count', 'cpu_cores']: try: v = int(v) except ValueError: v = 0 else: continue asset_dict[k] = v asset = get_object_or_none(Asset, id=id_) if is_uuid(id_) else None if not asset: try: if len(Asset.objects.filter(hostname=asset_dict.get('hostname'))): raise Exception(_('already exists')) asset = Asset.objects.create(**asset_dict) created.append(asset_dict['hostname']) assets.append(asset) except Exception as e: failed.append('%s: %s' % (asset_dict['hostname'], str(e))) else: for k, v in asset_dict.items(): if v: setattr(asset, k, v) try: asset.save() updated.append(asset_dict['hostname']) except Exception as e: failed.append('%s: %s' % (asset_dict['hostname'], str(e))) data = { 'created': created, 'created_info': 'Created {}'.format(len(created)), 'updated': updated, 'updated_info': 'Updated {}'.format(len(updated)), 'failed': failed, 'failed_info': 'Failed {}'.format(len(failed)), 'valid': True, 'msg': 'Created: {}. Updated: {}, Error: {}'.format( len(created), len(updated), len(failed)) } return self.render_json_response(data)
def form_valid(self, form): # logger.info('form_valid================================') f = form.cleaned_data['file'] det_result = chardet.detect(f.read()) f.seek(0) # reset file seek index data = f.read().decode(det_result['encoding']).strip( codecs.BOM_UTF8.decode()) csv_file = StringIO(data) reader = csv.reader(csv_file) csv_data = [row for row in reader] header_ = csv_data[0] fields = [ SystemUser._meta.get_field(name) for name in [ 'id', 'name', 'username', '_password', 'protocol', 'login_mode', 'priority', 'comment' ] ] mapping_reverse = {field.verbose_name: field.name for field in fields} attr = [mapping_reverse.get(n, None) for n in header_] if None in attr: data = { 'valid': False, 'msg': 'Must be same format as ' 'template or export file' } return self.render_json_response(data) created, updated, failed = [], [], [] for row in csv_data[1:]: if set(row) == {''}: continue user_dict = dict(zip(attr, row)) id_ = user_dict.pop('id') for k, v in user_dict.items(): user_dict[k] = v user = get_object_or_none(SystemUser, id=id_) if id_ and is_uuid(id_) else None if not user: try: with transaction.atomic(): user = SystemUser.objects.create(**user_dict) created.append(user_dict['username']) post_user_create.send(self.__class__, user=user) except Exception as e: failed.append('%s: %s' % (user_dict['username'], str(e))) else: for k, v in user_dict.items(): setattr(user, k, v) try: user.save() updated.append(user_dict['username']) except Exception as e: failed.append('%s: %s' % (user_dict['username'], str(e))) data = { 'created': created, 'created_info': 'Created {}'.format(len(created)), 'updated': updated, 'updated_info': 'Updated {}'.format(len(updated)), 'failed': failed, 'failed_info': 'Failed {}'.format(len(failed)), 'valid': True, 'msg': 'Created: {}. Updated: {}, Error: {}'.format( len(created), len(updated), len(failed)) } return self.render_json_response(data)
def form_valid(self, form): f = form.cleaned_data['file'] det_result = chardet.detect(f.read()) f.seek(0) # reset file seek index data = f.read().decode(det_result['encoding']).strip(codecs.BOM_UTF8.decode()) csv_file = StringIO(data) reader = csv.reader(csv_file) csv_data = [row for row in reader] header_ = csv_data[0] fields = [ User._meta.get_field(name) for name in [ 'id', 'name', 'username', 'email', 'role', 'wechat', 'phone', 'is_active', 'comment', ] ] mapping_reverse = {field.verbose_name: field.name for field in fields} mapping_reverse[_('User groups')] = 'groups' attr = [mapping_reverse.get(n, None) for n in header_] if None in attr: data = {'valid': False, 'msg': 'Must be same format as ' 'template or export file'} return self.render_json_response(data) created, updated, failed = [], [], [] for row in csv_data[1:]: if set(row) == {''}: continue user_dict = dict(zip(attr, row)) id_ = user_dict.pop('id') for k, v in user_dict.items(): if k in ['is_active']: if v.lower() == 'false': v = False else: v = bool(v) elif k == 'groups': groups_name = v.split(',') v = UserGroup.objects.filter(name__in=groups_name) else: continue user_dict[k] = v user = get_object_or_none(User, id=id_) if id_ and is_uuid(id_) else None if not user: try: with transaction.atomic(): groups = user_dict.pop('groups') user = User.objects.create(**user_dict) user.groups.set(groups) created.append(user_dict['username']) post_user_create.send(self.__class__, user=user) except Exception as e: failed.append('%s: %s' % (user_dict['username'], str(e))) else: for k, v in user_dict.items(): if k == 'groups': user.groups.set(v) continue if v: setattr(user, k, v) try: user.save() updated.append(user_dict['username']) except Exception as e: failed.append('%s: %s' % (user_dict['username'], str(e))) data = { 'created': created, 'created_info': 'Created {}'.format(len(created)), 'updated': updated, 'updated_info': 'Updated {}'.format(len(updated)), 'failed': failed, 'failed_info': 'Failed {}'.format(len(failed)), 'valid': True, 'msg': 'Created: {}. Updated: {}, Error: {}'.format( len(created), len(updated), len(failed)) } return self.render_json_response(data)
def form_valid(self, form): f = form.cleaned_data['file'] det_result = chardet.detect(f.read()) f.seek(0) # reset file seek index file_data = f.read().decode(det_result['encoding']).strip(codecs.BOM_UTF8.decode()) csv_file = StringIO(file_data) reader = csv.reader(csv_file) csv_data = [row for row in reader] fields = [ field for field in Asset._meta.fields if field.name not in [ 'date_created' ] ] header_ = csv_data[0] mapping_reverse = {field.verbose_name: field.name for field in fields} mapping_reverse[_('Asset groups')] = 'groups' attr = [mapping_reverse.get(n, None) for n in header_] if None in attr: data = {'valid': False, 'msg': 'Must be same format as ' 'template or export file'} return self.render_json_response(data) created, updated, failed = [], [], [] assets = [] for row in csv_data[1:]: if set(row) == {''}: continue asset_dict = dict(zip(attr, row)) id_ = asset_dict.pop('id', 0) for k, v in asset_dict.items(): if k == 'cluster': v = get_object_or_none(Cluster, name=v) elif k == 'is_active': v = bool(v) elif k == 'admin_user': v = get_object_or_none(AdminUser, name=v) elif k in ['port', 'cabinet_pos', 'cpu_count', 'cpu_cores']: try: v = int(v) except ValueError: v = 0 elif k == 'groups': groups_name = v.split(',') v = AssetGroup.objects.filter(name__in=groups_name) else: continue asset_dict[k] = v asset = get_object_or_none(Asset, id=id_) if is_uuid(id_) else None if not asset: try: groups = asset_dict.pop('groups') if len(Asset.objects.filter(hostname=asset_dict.get('hostname'))): raise Exception(_('already exists')) asset = Asset.objects.create(**asset_dict) asset.groups.set(groups) created.append(asset_dict['hostname']) assets.append(asset) except Exception as e: failed.append('%s: %s' % (asset_dict['hostname'], str(e))) else: for k, v in asset_dict.items(): if k == 'groups': asset.groups.set(v) continue if v: setattr(asset, k, v) try: asset.save() updated.append(asset_dict['hostname']) except Exception as e: failed.append('%s: %s' % (asset_dict['hostname'], str(e))) data = { 'created': created, 'created_info': 'Created {}'.format(len(created)), 'updated': updated, 'updated_info': 'Updated {}'.format(len(updated)), 'failed': failed, 'failed_info': 'Failed {}'.format(len(failed)), 'valid': True, 'msg': 'Created: {}. Updated: {}, Error: {}'.format( len(created), len(updated), len(failed)) } return self.render_json_response(data)
def form_valid(self, form): f = form.cleaned_data['file'] det_result = chardet.detect(f.read()) f.seek(0) # reset file seek index data = f.read().decode(det_result['encoding']).strip(codecs.BOM_UTF8.decode()) csv_file = StringIO(data) reader = csv.reader(csv_file) csv_data = [row for row in reader] header_ = csv_data[0] fields = [ CloudAccount._meta.get_field(name) for name in [ 'id', 'name', 'cloud_provider', 'accesskey_id', 'accesskey_secert', ] ] mapping_reverse = {field.verbose_name: field.name for field in fields} attr = [mapping_reverse.get(n, None) for n in header_] if None in attr: data = {'valid': False, 'msg': 'Must be same format as ' 'template or export file'} return self.render_json_response(data) created, updated, failed = [], [], [] for row in csv_data[1:]: if set(row) == {''}: continue account_dict = dict(zip(attr, row)) id_ = account_dict.pop('id') for k, v in account_dict.items(): account_dict[k] = v account = get_object_or_none(CloudAccount, id=id_) if id_ and is_uuid(id_) else None if not account: try: with transaction.atomic(): account = CloudAccount.objects.create(**account_dict) created.append(account_dict['name']) post_user_create.send(self.__class__, account=account) except Exception as e: failed.append('%s: %s' % (account_dict['name'], str(e))) else: for k, v in account_dict.items(): if v: setattr(account, k, v) try: account.save() updated.append(account_dict['name']) except Exception as e: failed.append('%s: %s' % (account['name'], str(e))) data = { 'created': created, 'created_info': 'Created {}'.format(len(created)), 'updated': updated, 'updated_info': 'Updated {}'.format(len(updated)), 'failed': failed, 'failed_info': 'Failed {}'.format(len(failed)), 'valid': True, 'msg': 'Created: {}. Updated: {}, Error: {}'.format( len(created), len(updated), len(failed)) } return self.render_json_response(data)
def has_permission(self, request, view): query_user_id = request.query_params.get('user') if not query_user_id or not is_uuid(query_user_id): return False query_user = current_org.get_members().filter(id=query_user_id).first() return bool(query_user)
def get_remote_app_asset(self, raise_exception=True): asset_id = self.attrs.get('asset') if is_uuid(asset_id): return Asset.objects.filter(id=asset_id).first() if raise_exception: raise ValueError("Remote App not has asset attr")