Python graphene.Union() Examples

The following are 10 code examples of graphene.Union(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module graphene , or try the search function .
Example #1
Source File: test_converter.py    From graphene-mongo with MIT License 6 votes vote down vote up
def test_should_generic_reference_convert_union():
    class A(MongoengineObjectType):
        class Meta:
            model = Article

    class E(MongoengineObjectType):
        class Meta:
            model = Editor

    class R(MongoengineObjectType):
        class Meta:
            model = Reporter

    generic_reference_field = convert_mongoengine_field(
        Reporter._fields["generic_reference"], registry.get_global_registry()
    )
    assert isinstance(generic_reference_field, graphene.Field)
    assert isinstance(generic_reference_field.type(), graphene.Union)
    assert generic_reference_field.type()._meta.types == (A, E) 
Example #2
Source File: union.py    From graphene with MIT License 5 votes vote down vote up
def __init_subclass_with_meta__(cls, types=None, **options):
        assert (
            isinstance(types, (list, tuple)) and len(types) > 0
        ), f"Must provide types for Union {cls.__name__}."

        _meta = UnionOptions(cls)
        _meta.types = types
        super(Union, cls).__init_subclass_with_meta__(_meta=_meta, **options) 
Example #3
Source File: union.py    From graphene with MIT License 5 votes vote down vote up
def get_type(cls):
        """
        This function is called when the unmounted type (Union instance)
        is mounted (as a Field, InputField or Argument)
        """
        return cls 
Example #4
Source File: entity.py    From graphene-federation with MIT License 5 votes vote down vote up
def get_entity_cls():
    class _Entity(Union):
        class Meta:
            types = tuple(custom_entities.values())
    return _Entity 
Example #5
Source File: dauphin_registry.py    From dagster with Apache License 2.0 5 votes vote down vote up
def create_union(metaclass, _registry):
    meta_class = type('Meta', (object,), {'types': ('__', '__')})
    Union = metaclass('Union', (graphene.Union,), {'Meta': meta_class})
    setattr(Union, '__dauphinCoreType', True)
    return Union 
Example #6
Source File: converter.py    From graphene-mongo with MIT License 5 votes vote down vote up
def convert_field_to_union(field, registry=None):

    _types = []
    for choice in field.choices:
        if isinstance(field, mongoengine.GenericReferenceField):
            _field = mongoengine.ReferenceField(get_document(choice))
        elif isinstance(field, mongoengine.GenericEmbeddedDocumentField):
            _field = mongoengine.EmbeddedDocumentField(choice)

        _field = convert_mongoengine_field(_field, registry)
        _type = _field.get_type()
        if _type:
            _types.append(_type.type)
        else:
            # TODO: Register type auto-matically here.
            pass

    if len(_types) == 0:
        return None

    # XXX: Use uuid to avoid duplicate name
    name = "{}_{}_union_{}".format(
        field._owner_document.__name__,
        field.db_field,
        str(uuid.uuid1()).replace("-", ""),
    )
    Meta = type("Meta", (object,), {"types": tuple(_types)})
    _union = type(name, (graphene.Union,), {"Meta": Meta})
    return graphene.Field(_union) 
Example #7
Source File: test_converter.py    From graphene-mongo with MIT License 5 votes vote down vote up
def test_should_generic_embedded_document_convert_union():
    class D(MongoengineObjectType):
        class Meta:
            model = EmbeddedArticle

    class F(MongoengineObjectType):
        class Meta:
            model = EmbeddedFoo

    class A(MongoengineObjectType):
        class Meta:
            model = Article

    class E(MongoengineObjectType):
        class Meta:
            model = Editor

    class R(MongoengineObjectType):
        class Meta:
            model = Reporter

    generic_embedded_document = convert_mongoengine_field(
        Reporter._fields["generic_embedded_document"], registry.get_global_registry()
    )
    assert isinstance(generic_embedded_document, graphene.Field)
    assert isinstance(generic_embedded_document.type(), graphene.Union)
    assert generic_embedded_document.type()._meta.types == (D, F) 
Example #8
Source File: streamfield.py    From wagtail-graphql with MIT License 5 votes vote down vote up
def stream_field_handler(stream_field_name: str, field_name: str, block_type_handlers: dict) -> StreamFieldHandlerType:
    # add Generic Scalars (default)
    if settings.LOAD_GENERIC_SCALARS:
        _scalar_block(GenericScalar)

    # Unions must reference NamedTypes, so for scalar types we need to create a new type to
    # encapsulate scalars, page links, images, snippets
    _create_root_blocks(block_type_handlers)

    types_ = list(block_type_handlers.values())
    for i, t in enumerate(types_):
        if isinstance(t, tuple):
            types_[i] = t[0]

    class Meta:
        types = tuple(set(types_))

    stream_field_type = type(
        stream_field_name + "Type",
        (graphene.Union, ),
        {
            'Meta': Meta,
            'resolve_type': _resolve_type
        }
    )

    def resolve_field(self, info: ResolveInfo):
        field = getattr(self, field_name)
        return [convert_block(block, block_type_handlers, info, field.is_lazy) for block in field.stream_data]

    return graphene.List(stream_field_type), resolve_field 
Example #9
Source File: dauphin_registry.py    From dagster with Apache License 2.0 4 votes vote down vote up
def __init__(self):
        self._typeMap = {}
        self.Field = create_registry_field(self)
        self.Argument = create_registry_argument(self)
        self.List = create_registry_list(self)
        self.NonNull = create_registry_nonnull(self)
        registering_metaclass = create_registering_metaclass(self)
        self.Union = create_union(registering_metaclass, self)
        self.Enum = create_enum(registering_metaclass)
        self.Mutation = graphene.Mutation

        # Not looping over GRAPHENE_TYPES in order to not fool lint
        self.ObjectType = create_registering_class(graphene.ObjectType, registering_metaclass)
        self.InputObjectType = create_registering_class(
            graphene.InputObjectType, registering_metaclass
        )
        self.Interface = create_registering_class(graphene.Interface, registering_metaclass)
        self.Scalar = create_registering_class(graphene.Scalar, registering_metaclass)

        # Not looping over GRAPHENE_BUILTINS in order to not fool lint
        self.String = graphene.String
        self.addType(graphene.String)
        self.Int = graphene.Int
        self.addType(graphene.Int)
        self.Float = graphene.Float
        self.addType(graphene.Float)
        self.Boolean = graphene.Boolean
        self.addType(graphene.Boolean)
        self.ID = graphene.ID
        self.addType(graphene.ID)
        self.GenericScalar = GenericScalar
        self.addType(GenericScalar) 
Example #10
Source File: fields.py    From graphene-mongo with MIT License 4 votes vote down vote up
def _field_args(self, items):
        def is_filterable(k):
            """
            Remove complex columns from input args at this moment.

            Args:
                k (str): field name.
            Returns:
                bool
            """

            if not hasattr(self.model, k):
                return False
            if isinstance(getattr(self.model, k), property):
                return False
            try:
                converted = convert_mongoengine_field(
                    getattr(self.model, k), self.registry
                )
            except MongoEngineConversionError:
                return False
            if isinstance(converted, (ConnectionField, Dynamic)):
                return False
            if callable(getattr(converted, "type", None)) and isinstance(
                converted.type(),
                (
                    FileFieldType,
                    PointFieldType,
                    MultiPolygonFieldType,
                    graphene.Union,
                    PolygonFieldType,
                ),
            ):
                return False
            if isinstance(converted, (graphene.List)) and issubclass(
                getattr(converted, "_of_type", None), graphene.Union
            ):
                return False

            return True

        def get_filter_type(_type):
            """
            Returns the scalar type.
            """
            if isinstance(_type, Structure):
                return get_filter_type(_type.of_type)
            return _type()

        return {k: get_filter_type(v.type) for k, v in items if is_filterable(k)}