def _convert_sa_to_graphene_enum(sa_enum, fallback_name=None): """Convert the given SQLAlchemy Enum type to a Graphene Enum type. The name of the Graphene Enum will be determined as follows: If the SQLAlchemy Enum is based on a Python Enum, use the name of the Python Enum. Otherwise, if the SQLAlchemy Enum is named, use the SQL name after conversion to a type name. Otherwise, use the given fallback_name or raise an error if it is empty. The Enum value names are converted to upper case if necessary. """ if not isinstance(sa_enum, SQLAlchemyEnumType): raise TypeError( "Expected sqlalchemy.types.Enum, but got: {!r}".format(sa_enum) ) enum_class = sa_enum.enum_class if enum_class: if all(to_enum_value_name(key) == key for key in enum_class.__members__): return Enum.from_enum(enum_class) name = enum_class.__name__ members = [ (to_enum_value_name(key), value.value) for key, value in enum_class.__members__.items() ] else: sql_enum_name = sa_enum.name if sql_enum_name: name = to_type_name(sql_enum_name) elif fallback_name: name = fallback_name else: raise TypeError("No type name specified for {!r}".format(sa_enum)) members = [(to_enum_value_name(key), key) for key in sa_enum.enums] return Enum(name, members)
def convert_choice_to_enum(type, column, registry=None): name = "{}_{}".format(column.table.name, column.name).upper() if isinstance(type.choices, EnumMeta): # type.choices may be Enum/IntEnum, in ChoiceType both presented as EnumMeta # do not use from_enum here because we can have more than one enum column in table return Enum(name, list((v.name, v.value) for v in type.choices)) else: return Enum(name, type.choices)
def convert_enum_to_enum(type, column, registry=None): enum_class = getattr(type, 'enum_class', None) if enum_class: # Check if an enum.Enum type is used graphene_type = Enum.from_enum(enum_class) else: # Nope, just a list of string options items = zip(type.enums, type.enums) graphene_type = Enum(type.name, items) return Field( graphene_type, description=get_column_doc(column), required=not (is_column_nullable(column)), )
def convert_form_field_with_choices(field, name=None, form=None): """ Helper method to convert a field to graphene Field type. :param name: form field's name :param field: form field to convert to :param form: field's form :return: graphene Field """ choices = getattr(field, "choices", None) # If is a choice field, but not depends on models if (not isinstance( field, (forms.ModelMultipleChoiceField, forms.ModelChoiceField)) and choices): if form: name = to_camel_case("{}_{}".format(get_form_name(form), field.label or name)) else: name = field.label or name name = to_camel_case(name.replace(" ", "_")) choices = list(get_choices(choices)) named_choices = [(c[0], c[1]) for c in choices] named_choices_descriptions = {c[0]: c[2] for c in choices} class EnumWithDescriptionsType(object): """Enum type definition""" @property def description(self): """Return field description""" return named_choices_descriptions[self.name] enum = Enum(name, list(named_choices), type=EnumWithDescriptionsType) return enum(description=field.help_text, required=field.required) # pylint: disable=E1102 return convert_form_field(field)
def convert_column_to_enum(type, column, registry=None): """A bug from graphene_sqlalchemy prevented any Enum The Enum class must be instantiated here """ name = '{}_{}'.format(column.table.name, column.name).upper() return Enum(name, type.choices, description=get_column_doc(column))()
def convert_django_field_with_choices(field, registry=None): if registry is not None: converted = registry.get_converted_field(field) if converted: return converted choices = getattr(field, "choices", None) # If we have choices and they contain keys as string... if choices and tuple_keys_contain_str(choices): meta = field.model._meta name = to_camel_case("{}_{}".format(meta.object_name, field.name)) choices = list(get_choices(choices)) named_choices = [(c[0], c[1]) for c in choices] named_choices_descriptions = {c[0]: c[2] for c in choices} class EnumWithDescriptionsType(object): @property def description(self): return named_choices_descriptions[self.name] enum = Enum(name, list(named_choices), type=EnumWithDescriptionsType) converted = enum(description=field.help_text, required=not field.null) # If we have no choices or they are integers else: converted = convert_django_field(field, registry) if registry is not None: registry.register_converted_field(field, converted) return converted
def get_type_for_enum(self, sql_type): assert isinstance(sql_type, SQLAlchemyEnumType), ( 'Only sqlalchemy.Enum objects can be registered as enum, ' 'received "{}"').format(sql_type) if sql_type.enum_class: name = sql_type.enum_class.__name__ items = [(key.upper(), value.value) for key, value in sql_type.enum_class.__members__.items()] else: name = sql_type.name if name: name = to_type_name(name) else: name = 'Enum{}'.format(len(self._registry_enums) + 1) items = [(key.upper(), key) for key in sql_type.enums] gql_type = self._registry_enums.get(name) if gql_type: if dict(items) != { key: value.value for key, value in gql_type._meta.enum.__members__.items() }: raise TypeError( 'Different enums with the same name {}'.format(name)) if not gql_type: gql_type = Enum(name, items) self._registry_enums[name] = gql_type return gql_type
def convert_choice_field_to_enum(field): """ Add support to convert ordering choices to Graphql enum. Label is used as enum name. """ registry = get_global_registry() converted = registry.get_converted_field(field) if converted: return converted def get_choices(choices): for value, help_text in choices: if value: name = convert_choice_name(value) description = help_text yield name, value, description name = to_camel_case(field.label) choices = list(get_choices(field.choices)) named_choices = [(c[0], c[1]) for c in choices] named_choices_descriptions = {c[0]: c[2] for c in choices} class EnumWithDescriptionsType(object): @property def description(self): return named_choices_descriptions[self.name] enum = Enum(name, list(named_choices), type=EnumWithDescriptionsType) converted = enum(description=field.help_text, required=field.required) registry.register_converted_field(field, converted) return converted
def convert_django_input_field_with_choices(field, registry=None, convert_choices_to_enum=True): if registry is not None: converted = registry.get_converted_field(field) if converted: return converted choices = getattr(field, "choices", None) if choices and convert_choices_to_enum: meta = field.model._meta name = to_camel_case("{}_{}".format(meta.object_name, field.name)) choices = list(get_choices(choices)) named_choices = [(c[0], c[1]) for c in choices] named_choices_descriptions = {c[0]: c[2] for c in choices} class EnumWithDescriptionsType(object): @property def description(self): return named_choices_descriptions[self.name] enum = Enum(name, list(named_choices), type=EnumWithDescriptionsType) required = not (field.blank or field.null) converted = enum(description=field.help_text, required=required) else: converted = convert_django_input_field(field, registry) if registry is not None: registry.register_converted_field(field, converted) return converted
def register_enum(self, cls): from enum import EnumMeta assert type( cls ) == EnumMeta, 'Only EnumMeta can be registered, received "{}"'.format( cls.__name__) self._registry_enum[cls] = Enum.from_enum(cls)
def convert_django_field_with_choices(field, registry=None, input_flag=None, nested_fields=False): choices = getattr(field, 'choices', None) if choices: meta = field.model._meta name = '{}_{}_{}'.format(meta.object_name, field.name, 'Enum') if input_flag: name = '{}_{}'.format(name, input_flag) name = to_camel_case(name) enum = registry.get_type_for_enum(name) if not enum: choices = list(get_choices(choices)) named_choices = [(c[0], c[1]) for c in choices] named_choices_descriptions = {c[0]: c[2] for c in choices} class EnumWithDescriptionsType(object): @property def description(self): return named_choices_descriptions[self.name] enum = Enum(name, list(named_choices), type=EnumWithDescriptionsType) registry.register_enum(name, enum) return enum(description=field.help_text or field.verbose_name, required=is_required(field) and input_flag == 'create') return convert_django_field(field, registry, input_flag, nested_fields)
class Arguments(): finding_id = String(required=True) justification = Argument(Enum('DeleteFindingJustification', [('DUPLICATED', 'DUPLICATED'), ('FALSE_POSITIVE', 'FALSE_POSITIVE'), ('NOT_REQUIRED', 'NOT_REQUIRED')]), required=True)
def convert_django_field_with_choices(field, registry=None): if registry is not None: converted = registry.get_converted_field(field) if converted: return converted choices = getattr(field, "choices", None) if choices: field_class = field.owner name = to_camel_case("{}_{}".format(field_class.__name__, field.name)) choices = list(get_choices(dict(choices))) named_choices = [(c[0], c[1]) for c in choices] named_choices_descriptions = {c[0]: c[2] for c in choices} class EnumWithDescriptionsType(object): @property def description(self): return named_choices_descriptions[self.name] enum = Enum(name, list(named_choices), type=EnumWithDescriptionsType) converted = enum(description=field.help_text, required=field.required) else: converted = convert_django_field(field, registry) if registry is not None: registry.register_converted_field(field, converted) return converted
def convert_with_choices(field, choices): meta = field.model._meta name = to_camel_case("{}_{}".format(meta.object_name, field.name)) choices = [(convert_choice_name(value), str(name)) for value, name in choices] enum = Enum(name, choices) return enum(required=not field.null)
class Arguments(): content = String(required=True) finding_id = String(required=True) parent = String(required=True) type = Argument(Enum('FindingCommentType', [('COMMENT', 'comment'), ('OBSERVATION', 'observation')]), required=True)
def convert_enum_to_enum(type, column, registry=None): try: items = type.enum_class.__members__.items() except AttributeError: items = zip(type.enums, type.enums) return Field(Enum(type.name, items), description=get_column_doc(column), required=not (is_column_nullable(column)))
def convert_peewee_field_with_choices(field, registry=None): choices = getattr(field, 'choices', None) if choices: meta = field.model_class._meta name = '{}_{}'.format(meta.name, field.name) graphql_choices = list(convert_choices(choices)) return Enum(name.upper(), graphql_choices, description=field.help_text) return convert_peewee_field(field, registry)
class Arguments(): companies = List(String, required=True) description = String(required=True) project_name = String(required=True) subscription = Argument(Enum('Subscription', [ ('Continuous', 'continuous'), ('Oneshot', 'oneshot')]), required=False) has_forces = Boolean(required=False)
def convert_django_field_with_choices(field, registry=None): choices = getattr(field, 'choices', None) if choices: meta = field.model._meta name = '{}{}'.format(meta.object_name, field.name.capitalize()) graphql_choices = list(convert_choices(choices)) enum = Enum(name, list(graphql_choices)) return enum(description=field.help_text) return convert_django_field(field, registry)
class Arguments(): description = String(required=True) evidence_id = Argument(Enum('EvidenceDescriptionType', [('EVIDENCE1', 'evidence_route_1'), ('EVIDENCE2', 'evidence_route_2'), ('EVIDENCE3', 'evidence_route_3'), ('EVIDENCE4', 'evidence_route_4'), ('EVIDENCE5', 'evidence_route_5')]), required=True) finding_id = String(required=True)
def convert_choices_to_named_enum_with_descriptions(name, choices): choices = list(get_choices(choices)) named_choices = [(c[0], c[1]) for c in choices] named_choices_descriptions = {c[0]: c[2] for c in choices} class EnumWithDescriptionsType(object): @property def description(self): return named_choices_descriptions[self.name] return Enum(name, list(named_choices), type=EnumWithDescriptionsType)
class Arguments(): acceptance_date = String() bts_url = String() finding_id = String(required=True) treatment = String( Enum('UpdateClientDescriptionTreatment', [('IN PROGRESS', 'IN PROGRESS'), ('ACCEPTED', 'ACCEPTED'), ('ACCEPTED_UNDEFINED', 'ACCEPTED_UNDEFINED')]), required=True) justification = String(required=True) acceptance_status = String()
class Arguments(): """Arguments of the class.""" id = String(required=True) # noqa pylint: disable=invalid-name finding_id = String(required=True) justification = Argument( Enum('DeleteVulnerabilityJustification', [('DUPLICATED', 'DUPLICATED'), ('FALSE_POSITIVE', 'FALSE_POSITIVE'), ('REPORTING_ERROR', 'REPORTING_ERROR')]), required=True)
class query(ObjectType): entries = List( etyp, field = NonNull(Enum('field', emap)), query = NonNull(String), query_type = NonNull(Enum.from_enum(querytypes)), size = Int() ) ids = List( etyp, ids = List(NonNull(String)) ) def resolve_ids(self, _, ids): return search.ids(elex, ids) def resolve_entries(self, _, field, query, query_type, size = 10): field = next(i for i in emap if i[1] == field)[0] query_type = querytypes(query_type).name return search.entries(elex, field, query, query_type, size)
class Arguments(): cwe = String(required=False) description = String(required=False) origin = String(required=False) project_name = String(required=True) recommendation = String(required=False) requirements = String(required=False) risk = String(required=False) threat = String(required=False) title = String(required=True) type = Argument(Enum('FindingType', [('SECURITY', 'SECURITY'), ('HYGIENE', 'HYGIENE')]), required=False)
def _sort_enum_for_model(cls, name=None, symbol_name=_symbol_name): name = name or cls.__name__ + 'SortEnum' items = [] default = [] for column in inspect(cls).columns.values(): asc_name = symbol_name(column.name, True) asc_value = EnumValue(asc_name, column.asc()) desc_name = symbol_name(column.name, False) desc_value = EnumValue(desc_name, column.desc()) if column.primary_key: default.append(asc_value) items.extend(((asc_name, asc_value), (desc_name, desc_value))) return Enum(name, items), default
def convert_choices_field(field, choices, required=None): meta = field.model._meta name = to_camel_case("{}_{}".format(meta.object_name, field.name)) choices = list(get_choices(choices)) named_choices = [(c[0], c[1]) for c in choices] named_choices_descriptions = {c[0]: c[2] for c in choices} class EnumWithDescriptionsType(object): @property def description(self): return named_choices_descriptions[self.name] enum = Enum(name, list(named_choices), type=EnumWithDescriptionsType) return enum(description=field.help_text, required=required)
def column_from_classes(models): """Create Graphene List to select the columns from SQLAlchemy classes""" if not isinstance(models, list): models = [models] items = list() for model in models: try: for col in model.__table__.c: items.extend([(str(col).replace('.', '_'), col)]) except AttributeError as error: raise (error) return List(Enum(models[0].__name__ + 'SearchEnum', items))
def convert_choices_field(field, choices, required=None): meta = field.model._meta name = to_camel_case("{}_{}".format(meta.object_name, field.name)) choices = list(get_choices(choices)) named_choices = [(c[0], c[1]) for c in choices] named_choices_descriptions = {c[0]: c[2] for c in choices} class EnumWithDescriptionsType(object): @property def description(self): return named_choices_descriptions[self.name] enum = Enum(name, list(named_choices), type=EnumWithDescriptionsType) # Note that we do not instantiate the field here, so we can store it un-instantiated in the registry. # This is the allow different parameters (e.g. `required`) to be passed to the field. return enum
def convert_django_field_with_choices(field, registry=None): choices = getattr(field, 'choices', None) if choices: meta = field.model._meta name = to_camel_case('{}_{}'.format(meta.object_name, field.name)) choices = list(get_choices(choices)) named_choices = [(c[0], c[1]) for c in choices] named_choices_descriptions = {c[0]: c[2] for c in choices} class EnumWithDescriptionsType(object): @property def description(self): return named_choices_descriptions[self.name] enum = Enum(name, list(named_choices), type=EnumWithDescriptionsType) return enum(description=field.help_text, required=not field.null) return convert_django_field(field, registry)