def update(cls, root, info, **kwargs): data = kwargs.get(cls._meta.input_field_name) request_type = info.context.META.get("CONTENT_TYPE", '') if "multipart/form-data" in request_type: data.update( {name: value for name, value in info.context.FILES.items()}) pk = data.pop('id') old_obj = get_Object_or_None(cls._meta.model, pk=pk) if old_obj: nested_objs = cls.manage_nested_fields(data, root, info) serializer = cls._meta.serializer_class( old_obj, data=data, partial=True, **cls.get_serializer_kwargs(root, info, **kwargs)) ok, obj = cls.save(serializer, root, info) if not ok: return cls.get_errors(obj) elif nested_objs: [ getattr(obj, field).add(*objs) for field, objs in nested_objs.items() ] return cls.perform_mutate(obj, info) else: return cls.get_errors([ ErrorType(field='id', messages=[ 'A {} obj with id: {} do not exist'.format( cls._meta.model.__name__, pk) ]) ])
def mutate(self, info, email): errors = dict() email = email try: user = User.objects.get(email=email) except User.DoesNotExist: errors['email'] = [EMAIL_ADDRESS_DOES_NOT_EXIST] return RestorePasswordRequest( success=False, field_errors=ErrorType.from_errors(errors)) if not user.is_active or user.is_deleted: return RestorePasswordRequest( message=MessageType(title=RESTORE_PASSWORD_EMAIL_ACTIVE, description=RESTORE_PASSWORD_EMAIL_ACTIVE, type=WARNING_MESSAGE_TYPE)) domain = get_domain(info.context) send_restore_password_link.delay( user_id=user.pk, email=email, domain=domain, ) return RestorePasswordRequest(success=True, message=MessageType( title='RESTORE_PASSWORD_EMAIL_TITLE', description='RESTORE_PASSWORD_EMAIL', type=SUCCESS_MESSAGE_TYPE))
def perform_delete_mutate(cls, info, id): try: obj = cls._meta.model._default_manager.get(pk=id) obj.delete() kwargs = {cls._meta.return_field_name: obj} return cls(errors=[], **kwargs) except cls._meta.model.DoesNotExist: return cls(errors=ErrorType.from_errors({'id': ['Not found.']}))
def mutate_and_get_payload(cls, root, info, **input): form = cls.get_form(root, info, **input) if form.is_valid(): return cls.perform_mutate(form, info) else: errors = ErrorType.from_errors(form.errors) return cls(errors=errors, **form.data)
def wrapper(cls, root, info, **kwargs): if not _check_permissions(info, permissions): return cls.get_errors( [ ErrorType( field="permission", messages=["Permission Denied!"], ) ] ) return func(cls, root, info, **kwargs)
def save(cls, serialized_obj, root, info, **kwargs): if serialized_obj.is_valid(): obj = serialized_obj.save() return True, obj else: errors = [ ErrorType(field=key, messages=value) for key, value in serialized_obj.errors.items() ] return False, errors
def _handle_errors(self, e): if isinstance(e, Serializer_ValidationError): errors = self.error_builder(e.detail.serializer) return self.get_errors(errors) if isinstance(e, Django_ValidationError): errors = self.django_error_builder(e.error_list) return self.get_errors(errors) messages = e.__str__() return self.get_errors([ErrorType( field="id", messages=[messages], )])
def update(cls, root, info, **kwargs): data = kwargs.pop("input") profile_data = data.pop("profile", {}) profile_data["updater"] = info.context.user.id pk = data.pop("id") group = get_Object_or_None(Group, pk=pk) if not group: return cls.get_errors([ ErrorType( field="id", messages=[ "A {} obj with id: {} do not exist".format( "Group", pk) ], ) ]) group_ser = GroupSerializer(instance=group, data=data, partial=True) if not group_ser.is_valid(): errors = [ ErrorType(field=key, messages=value) for key, value in group_ser.errors.items() ] return cls.get_errors(errors) profile = GroupProfile.objects.filter(group_id=group.id) profile_ser = GroupProfileSerializer(instance=profile, data=profile_data, partial=True) ok, profile = cls.save(profile_ser, root, info) if not ok: return cls.get_errors(profile) group = group_ser.save() profile_ser.save() return cls.perform_mutate(group, info)
def mutate(cls, root, info, id): try: obj = cls._meta.model.objects.get(id=id) obj.delete() obj.id = id return cls.perform_mutate(obj, info) except ObjectDoesNotExist: return cls.get_errors([ ErrorType( field="id", messages=[ "A {} obj with id {} do not exist".format( cls._meta.model.__name__, id) ], ) ])
def delete(cls, root, info, **kwargs): pk = kwargs.get('id') old_obj = get_Object_or_None(cls._meta.model, pk=pk) if old_obj: old_obj.delete() old_obj.id = pk return cls.perform_mutate(old_obj, info) else: return cls.get_errors([ ErrorType(field='id', messages=[ 'A {} obj with id {} do not exist'.format( cls._meta.model.__name__, pk) ]) ])
def mutate(self, info, new_configuration: ConfigurationUpdateGenericType): instance = Configuration.objects.first() fields = {"system_secret": new_configuration.system_secret} serializer = ConfigurationSerializer(instance=instance, data=fields) if serializer.is_valid(): config = serializer.save() return UpdateConfiguration(configuration=config, ok=True, errors=None) else: errors = [ ErrorType(field=key, messages=value) for key, value in serializer.errors.items() ] return UpdateConfiguration(realm=None, ok=False, errors=errors)
def mutate_and_get_payload(cls, root, info, **input): if cls._meta.is_relay: input = normalize_global_ids(cls._meta.model, input) cls.check_permissions(info) if cls._meta.deleting: id = input.get("id") return cls.perform_delete_mutate(info, id) form = cls.get_form(root, info, **input) if form.is_valid(): return cls.perform_mutate(form, info) else: errors = ErrorType.from_errors(form.errors) return cls(errors=errors)
def update(cls, root, info, **kwargs): """ @description: 更新用户 @param {type} @return: """ data = kwargs.get("input") profile_data = data.pop("profile", {}) # 只有教师与管理员才可以修改其他用户的信息 # 否则就算是传入了id也只能修改自己的信息 pk = data.pop("id") user = info.context.user if user.is_staff or user.groups.all().filter(name="教师").first(): user = get_Object_or_None(User, pk=pk) if not user: return cls.get_errors(__fill_error("id", "用户不存在!")) if user.groups.all().filter(name="教师").first(): user = info.context.user profile_data["updater"] = user.id user_ser = UserSerializer(instance=user, data=data, partial=True) if not user_ser.is_valid(): errors = [ ErrorType(field=key, messages=value) for key, value in user_ser.errors.items() ] return cls.get_errors(errors) profile = UserProfile.objects.filter(user_id=user.id).first() profile_ser = None if not profile: profile_ser = UserProfileSerializer(data=profile_data) else: profile_ser = UserProfileSerializer(instance=profile, data=profile_data, partial=True) ok, profile = cls.save(profile_ser, root, info) if not ok: return cls.get_errors(profile) user_ser.save() return cls.perform_mutate(user, info)
def save(cls, serialized_obj, root, info, **kwargs): """ graphene-django v3 now returns the full Enum object, instead of its value. We need to get its value before validating the submitted data. """ for key in serialized_obj.initial_data: if "Enum" in type(serialized_obj.initial_data[key]).__name__: serialized_obj.initial_data[key] = serialized_obj.initial_data[ key].value if serialized_obj.is_valid(): obj = serialized_obj.save() return True, obj else: errors = [ ErrorType(field=key, messages=value) for key, value in serialized_obj.errors.items() ] return False, errors
def mutate_and_get_payload(cls, root, info, **input): if hasattr(cls, 'has_permission') and callable( getattr(cls, 'has_permission')): if not cls.has_permission(root, info, input): # errors = ErrorType.from_errors( # {'permission': [_('Você não tem permissão para isso!')]}) # return cls(errors=errors) raise PermissionDenied() search_key = 'id' convert_hash_id_to_plain_id(input, search_key) # return super(RNASerializerMutation, cls).mutate_and_get_payload(root, info, **input) kwargs = cls.get_serializer_kwargs(root, info, **input) serializer = cls._meta.serializer_class(**kwargs) if serializer.is_valid(): return cls.perform_mutate(serializer, info) else: errors = ErrorType.from_errors( serializer_errors_to_graphql(serializer.errors)) return cls(errors=errors)
def error_builder(cls, serialized_obj): errors = [ ErrorType(field=key, messages=value) for key, value in serialized_obj.errors.items() ] return errors
def django_error_builder(cls, error_list): errors = [ErrorType(messages=item.messages) for item in error_list] return errors
def construct_error( cls, message, field=None, ): return list(ErrorType(field=field, messages=list(message)))
def __fill_error(field, msg): return [ErrorType( field=field, messages=[msg], )]
def update(cls, root, info, **kwargs): data = kwargs.get("input") profile_data = data.pop("profile", None) data = kwargs.get("input") profile_data = data.pop("profile", {}) # 只有教师才可以修改其他用户的信息 # 否则就算是传入了id也只能修改自己的信息 pk = data.pop("id") user = info.context.user if user.is_staff: user = get_Object_or_None(User, pk=pk) if not user: return cls.get_errors(__fill_error("id", "用户不存在!")) if user.is_staff: user = info.context.user profile_data["updater"] = user.id # 如果更改了name属性,则先检查组内是否有同名组 name = profile_data.get("name", None) if name: if get_Object_or_None(group, name=name): return cls.get_errors(__fill_error("name", "已经存在同名组:" + name)) user_ser = UserSerializer(instance=user, data=data, partial=True) if not user_ser.is_valid(): errors = [ ErrorType(field=key, messages=value) for key, value in user_ser.errors.items() ] return cls.get_errors(errors) group = user.groups.all().filter(name=user.profile.name).first() group_ser = GroupSerializer(instance=group, data={"name": name}, partial=True) if not group_ser.is_valid(): errors = [ ErrorType(field=key, messages=value) for key, value in group_ser.errors.items() ] return cls.get_errors(errors) gp_ser = GroupProfileSerializer(instance=group.profile, data={}, partial=True) if not gp_ser.is_valid(): errors = [ ErrorType(field=key, messages=value) for key, value in gp_ser.errors.items() ] return cls.get_errors(errors) profile = UserProfile.objects.filter(user_id=user.id).first() profile_ser = None if not profile: profile_ser = UserProfileSerializer(data=profile_data) else: profile_ser = UserProfileSerializer(instance=profile, data=profile_data, partial=True) ok, profile = cls.save(profile_ser, root, info) if not ok: return cls.get_errors(profile) user_ser.save() group_ser.save() gp_ser.save() return cls.perform_mutate(user, info)
def get_errors(errors): error_list = list() errors = camelize(errors) for key, value in errors.items(): error_list.append(ErrorType(field=key, messages=value[0])) return error_list