Python graphene.Field() Examples

The following are 30 code examples of graphene.Field(). 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: converter.py    From graphene-mongo with MIT License 6 votes vote down vote up
def convert_lazy_field_to_dynamic(field, registry=None):
    model = field.document_type

    def lazy_resolver(root, *args, **kwargs):
        if getattr(root, field.name or field.db_name):
            return getattr(root, field.name or field.db_name).fetch()

    def dynamic_type():
        _type = registry.get_type_for_model(model)
        if not _type:
            return None
        return graphene.Field(
            _type,
            resolver=lazy_resolver,
            description=get_field_description(field, registry),
        )

    return graphene.Dynamic(dynamic_type) 
Example #2
Source File: test_relay_query.py    From graphene-mongo with MIT License 6 votes vote down vote up
def test_should_filter_by_id(fixtures):
    # Notes: https://goo.gl/hMNRgs
    class Query(graphene.ObjectType):
        reporter = Node.Field(nodes.ReporterNode)

    query = """
        query ReporterQuery {
            reporter (id: "UmVwb3J0ZXJOb2RlOjE=") {
                id,
                firstName,
                awards
            }
        }
    """
    expected = {
        "reporter": {
            "id": "UmVwb3J0ZXJOb2RlOjE=",
            "firstName": "Allen",
            "awards": ["2010-mvp"],
        }
    }
    schema = graphene.Schema(query=Query)
    result = schema.execute(query)
    assert not result.errors
    assert result.data == expected 
Example #3
Source File: converter.py    From graphene-gae with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def convert_local_structured_property(ndb_structured_property, registry=None):
    is_required = ndb_structured_property._required
    is_repeated = ndb_structured_property._repeated
    model = ndb_structured_property._modelclass
    name = ndb_structured_property._code_name

    def dynamic_type():
        _type = registry.get_type_for_model(model)
        if not _type:
            return None

        if is_repeated:
            _type = List(_type)

        if is_required:
            _type = NonNull(_type)

        return Field(_type)

    field = Dynamic(dynamic_type)
    return ConversionResult(name=name, field=field) 
Example #4
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 #5
Source File: objecttype.py    From graphene with MIT License 6 votes vote down vote up
def __new__(cls, name_, bases, namespace, **options):
        # Note: it's safe to pass options as keyword arguments as they are still type-checked by ObjectTypeOptions.

        # We create this type, to then overload it with the dataclass attrs
        class InterObjectType:
            pass

        base_cls = super().__new__(
            cls, name_, (InterObjectType,) + bases, namespace, **options,
        )
        if base_cls._meta:
            fields = [
                (
                    key,
                    "typing.Any",
                    field(
                        default=field_value.default_value
                        if isinstance(field_value, Field)
                        else None
                    ),
                )
                for key, field_value in base_cls._meta.fields.items()
            ]
            dataclass = make_dataclass(name_, fields, bases=())
            InterObjectType.__init__ = dataclass.__init__
            InterObjectType.__eq__ = dataclass.__eq__
            InterObjectType.__repr__ = dataclass.__repr__
        return base_cls 
Example #6
Source File: test_converter.py    From graphene-mongo with MIT License 6 votes vote down vote up
def test_should_self_reference_convert_dynamic():
    class P(MongoengineObjectType):
        class Meta:
            model = Player
            interfaces = (graphene.Node,)

    dynamic_field = convert_mongoengine_field(
        Player._fields["opponent"], P._meta.registry
    )
    assert isinstance(dynamic_field, graphene.Dynamic)
    graphene_type = dynamic_field.get_type()
    assert isinstance(graphene_type, graphene.Field)
    assert graphene_type.type == P

    graphene_field = convert_mongoengine_field(
        Player._fields["players"], P._meta.registry
    )
    assert isinstance(graphene_field, MongoengineConnectionField) 
Example #7
Source File: filters.py    From graphene-sqlalchemy-filter with MIT License 6 votes vote down vote up
def _is_graphene_enum(obj: 'Any') -> bool:
        """
        Return whether 'obj' is a enum.

        Args:
            obj: lambda or graphene.Field

        Returns:
            boolean

        """
        if gqls_version < (2, 2, 0):
            # https://github.com/graphql-python/graphene-sqlalchemy/blob/v2.1.2/graphene_sqlalchemy/converter.py#L147
            return isinstance(obj, graphene.Field) and isinstance(
                obj._type, graphene.types.enum.EnumMeta
            )
        elif gqls_version == (2, 2, 0):
            # https://github.com/graphql-python/graphene-sqlalchemy/blob/db3e9f4c3baad3e62c113d4a9ddd2e3983d324f2/graphene_sqlalchemy/converter.py#L150
            return isinstance(obj, graphene.Field) and callable(obj._type)
        else:
            # https://github.com/graphql-python/graphene-sqlalchemy/blob/17d535efba03070cbc505d915673e0f24d9ca60c/graphene_sqlalchemy/converter.py#L216
            return callable(obj) and obj.__name__ == '<lambda>' 
Example #8
Source File: service.py    From graphene-federation with MIT License 6 votes vote down vote up
def get_service_query(schema):
    sdl_str = get_sdl(schema, custom_entities)

    class _Service(ObjectType):
        sdl = String()

        def resolve_sdl(parent, _):
            return sdl_str

    class ServiceQuery(ObjectType):
        _service = Field(_Service, name="_service")

        def resolve__service(parent, info):
            return _Service()

    return ServiceQuery 
Example #9
Source File: test_converter.py    From graphene-mongo with MIT License 5 votes vote down vote up
def test_should_multipolygon_convert_field():
    graphene_type = convert_mongoengine_field(mongoengine.MultiPolygonField())
    assert isinstance(graphene_type, graphene.Field)
    assert graphene_type.type == advanced_types.MultiPolygonFieldType
    assert isinstance(graphene_type.type.type, graphene.String)
    assert isinstance(graphene_type.type.coordinates, graphene.List) 
Example #10
Source File: dataset.py    From gigantum-client with MIT License 5 votes vote down vote up
def resolve_backend_configuration(self, info):
        """Field to get current configuration. If values are None, still needs to be set."""
        return info.context.dataset_loader.load(f"{get_logged_in_username()}&{self.owner}&{self.name}").then(
            lambda dataset: self.helper_resolve_backend_configuration(dataset)) 
Example #11
Source File: dataset.py    From gigantum-client with MIT License 5 votes vote down vote up
def resolve_content_hash_mismatches(self, info):
        """Field to look up any content hash mismatches. Note this can be slow for big datasets!"""
        return info.context.dataset_loader.load(f"{get_logged_in_username()}&{self.owner}&{self.name}").then(
            lambda dataset: dataset.backend.verify_contents(dataset, logger.info)) 
Example #12
Source File: converter.py    From graphene-mongo with MIT License 5 votes vote down vote up
def convert_point_to_field(field, registry=None):
    return graphene.Field(advanced_types.PointFieldType) 
Example #13
Source File: converter.py    From graphene-mongo with MIT License 5 votes vote down vote up
def convert_polygon_to_field(field, registry=None):
    return graphene.Field(advanced_types.PolygonFieldType) 
Example #14
Source File: test_converter.py    From graphene-mongo with MIT License 5 votes vote down vote up
def test_should_lazy_reference_convert_dynamic():
    class P(MongoengineObjectType):
        class Meta:
            model = Publisher
            interfaces = (graphene.Node,)

    dynamic_field = convert_mongoengine_field(
        Editor._fields["company"], P._meta.registry
    )

    assert isinstance(dynamic_field, graphene.Dynamic)
    graphene_type = dynamic_field.get_type()
    assert isinstance(graphene_type, graphene.Field)
    assert graphene_type.type == P 
Example #15
Source File: test_converter.py    From graphene-mongo with MIT License 5 votes vote down vote up
def test_should_polygon_covert_field():
    graphene_type = convert_mongoengine_field(mongoengine.PolygonField())
    assert isinstance(graphene_type, graphene.Field)
    assert graphene_type.type == advanced_types.PolygonFieldType
    assert isinstance(graphene_type.type.type, graphene.String)
    assert isinstance(graphene_type.type.coordinates, graphene.List) 
Example #16
Source File: object_types.py    From flask-unchained with MIT License 5 votes vote down vote up
def _get_field_resolver(field: graphene.Field):
    def _get(self, info, **kwargs):
        return field.type._meta.model.query.get_by(**kwargs)

    return _get 
Example #17
Source File: test_converter.py    From graphene-mongo with MIT License 5 votes vote down vote up
def test_should_reference_convert_dynamic():
    class E(MongoengineObjectType):
        class Meta:
            model = Editor
            interfaces = (graphene.Node,)

    dynamic_field = convert_mongoengine_field(
        EmbeddedArticle._fields["editor"], E._meta.registry
    )
    assert isinstance(dynamic_field, graphene.Dynamic)
    graphene_type = dynamic_field.get_type()
    assert isinstance(graphene_type, graphene.Field)
    assert graphene_type.type == E 
Example #18
Source File: test_relay_query.py    From graphene-mongo with MIT License 5 votes vote down vote up
def test_should_filter_through_inheritance(fixtures):
    class Query(graphene.ObjectType):
        node = Node.Field()
        children = MongoengineConnectionField(nodes.ChildNode)

    query = """
        query ChildrenQuery {
            children(bar: "bar") {
                edges {
                    node {
                        bar,
                        baz,
                        loc {
                             type,
                             coordinates
                        }
                    }
                }
            }
        }
    """
    expected = {
        "children": {
            "edges": [
                {
                    "node": {
                        "bar": "bar",
                        "baz": "baz",
                        "loc": {"type": "Point", "coordinates": [10.0, 20.0]},
                    }
                }
            ]
        }
    }
    schema = graphene.Schema(query=Query)
    result = schema.execute(query)
    assert not result.errors
    assert result.data == expected 
Example #19
Source File: test_relay_query.py    From graphene-mongo with MIT License 5 votes vote down vote up
def test_should_get_queryset_returns_dict_filters(fixtures):
    class Query(graphene.ObjectType):
        node = Node.Field()
        articles = MongoengineConnectionField(
            nodes.ArticleNode, get_queryset=lambda *_, **__: {"headline": "World"}
        )

    query = """
           query ArticlesQuery {
               articles {
                   edges {
                       node {
                           headline,
                           pubDate,
                           editor {
                               firstName
                           }
                       }
                   }
               }
           }
       """
    expected = {
        "articles": {
            "edges": [
                {
                    "node": {
                        "headline": "World",
                        "editor": {"firstName": "Grant"},
                        "pubDate": "2020-01-01T00:00:00",
                    }
                }
            ]
        }
    }
    schema = graphene.Schema(query=Query)
    result = schema.execute(query)
    assert not result.errors
    assert result.data == expected 
Example #20
Source File: dataset.py    From gigantum-client with MIT License 5 votes vote down vote up
def resolve_backend_is_configured(self, info):
        """Field to check if a dataset backend is fully configured"""
        return info.context.dataset_loader.load(f"{get_logged_in_username()}&{self.owner}&{self.name}").then(
            lambda dataset: self._helper_configure_default_parameters(dataset).backend.is_configured) 
Example #21
Source File: object_types.py    From flask-unchained with MIT License 5 votes vote down vote up
def __new__(mcs, name, bases, clsdict):
        fields, lists = [], []
        for attr, value in clsdict.items():
            resolver = f'resolve_{attr}'
            if attr.startswith('_') or resolver in clsdict:
                continue
            elif isinstance(value, graphene.Field):
                fields.append((resolver, value))
            elif isinstance(value, graphene.List):
                lists.append((resolver, value))

        clsdict.update({k: _get_field_resolver(v) for k, v in fields})
        clsdict.update({k: _get_list_resolver(v) for k, v in lists})

        return super().__new__(mcs, name, bases, clsdict) 
Example #22
Source File: converter.py    From graphene-mongo with MIT License 5 votes vote down vote up
def convert_field_to_dynamic(field, registry=None):
    model = field.document_type

    def dynamic_type():
        _type = registry.get_type_for_model(model)
        if not _type:
            return None
        return graphene.Field(_type, description=get_field_description(field, registry))

    return graphene.Dynamic(dynamic_type) 
Example #23
Source File: test_converter.py    From graphene-sqlalchemy with MIT License 5 votes vote down vote up
def test_should_onetoone_convert_field():
    class A(SQLAlchemyObjectType):
        class Meta:
            model = Article
            interfaces = (Node,)

    dynamic_field = convert_sqlalchemy_relationship(
        Reporter.favorite_article.property, A, default_connection_field_factory, True, 'orm_field_name',
    )
    assert isinstance(dynamic_field, graphene.Dynamic)
    graphene_type = dynamic_field.get_type()
    assert isinstance(graphene_type, graphene.Field)
    assert graphene_type.type == A 
Example #24
Source File: test_converter.py    From graphene-sqlalchemy with MIT License 5 votes vote down vote up
def test_should_manytoone_convert_connectionorlist_connection():
    class A(SQLAlchemyObjectType):
        class Meta:
            model = Reporter
            interfaces = (Node,)

    dynamic_field = convert_sqlalchemy_relationship(
        Article.reporter.property, A, default_connection_field_factory, True, 'orm_field_name',
    )
    assert isinstance(dynamic_field, graphene.Dynamic)
    graphene_type = dynamic_field.get_type()
    assert isinstance(graphene_type, graphene.Field)
    assert graphene_type.type == A 
Example #25
Source File: test_converter.py    From graphene-sqlalchemy with MIT License 5 votes vote down vote up
def test_should_manytoone_convert_connectionorlist_list():
    class A(SQLAlchemyObjectType):
        class Meta:
            model = Reporter

    dynamic_field = convert_sqlalchemy_relationship(
        Article.reporter.property, A, default_connection_field_factory, True, 'orm_field_name',
    )
    assert isinstance(dynamic_field, graphene.Dynamic)
    graphene_type = dynamic_field.get_type()
    assert isinstance(graphene_type, graphene.Field)
    assert graphene_type.type == A 
Example #26
Source File: test_converter.py    From graphene-sqlalchemy with MIT License 5 votes vote down vote up
def test_should_manytomany_convert_connectionorlist_list():
    class A(SQLAlchemyObjectType):
        class Meta:
            model = Pet

    dynamic_field = convert_sqlalchemy_relationship(
        Reporter.pets.property, A, default_connection_field_factory, True, 'orm_field_name',
    )
    assert isinstance(dynamic_field, graphene.Dynamic)
    graphene_type = dynamic_field.get_type()
    assert isinstance(graphene_type, graphene.Field)
    assert isinstance(graphene_type.type, graphene.List)
    assert graphene_type.type.of_type == A 
Example #27
Source File: test_query.py    From graphene-sqlalchemy with MIT License 5 votes vote down vote up
def test_custom_identifier(session):
    add_test_data(session)

    class EditorNode(SQLAlchemyObjectType):
        class Meta:
            model = Editor
            interfaces = (Node,)

    class Query(graphene.ObjectType):
        node = Node.Field()
        all_editors = SQLAlchemyConnectionField(EditorNode.connection)

    query = """
        query {
          allEditors {
            edges {
                node {
                    id
                    name
                }
            }
          },
          node(id: "RWRpdG9yTm9kZTox") {
            ...on EditorNode {
              name
            }
          }
        }
    """
    expected = {
        "allEditors": {"edges": [{"node": {"id": "RWRpdG9yTm9kZTox", "name": "Jack"}}]},
        "node": {"name": "Jack"},
    }

    schema = graphene.Schema(query=Query)
    result = schema.execute(query, context_value={"session": session})
    assert not result.errors
    result = to_std_dicts(result.data)
    assert result == expected 
Example #28
Source File: test_query_enums.py    From graphene-sqlalchemy with MIT License 5 votes vote down vote up
def test_py_enum_as_argument(session):
    add_test_data(session)

    class PetType(SQLAlchemyObjectType):
        class Meta:
            model = Pet

    class Query(graphene.ObjectType):
        pet = graphene.Field(
            PetType,
            kind=graphene.Argument(PetType._meta.fields["hair_kind"].type.of_type),
        )

        def resolve_pet(self, _info, kind=None):
            query = session.query(Pet)
            if kind:
                # enum arguments are expected to be strings, not PyEnums
                query = query.filter(Pet.hair_kind == HairKind(kind))
            return query.first()

    query = """
        query PetQuery($kind: HairKind) {
          pet(kind: $kind) {
            name,
            petKind
            hairKind
          }
        }
    """

    schema = graphene.Schema(query=Query)
    result = schema.execute(query, variables={"kind": "SHORT"})
    assert not result.errors
    expected = {"pet": {"name": "Garfield", "petKind": "CAT", "hairKind": "SHORT"}}
    assert result.data == expected
    result = schema.execute(query, variables={"kind": "LONG"})
    assert not result.errors
    expected = {"pet": {"name": "Lassie", "petKind": "DOG", "hairKind": "LONG"}}
    result = to_std_dicts(result.data)
    assert result == expected 
Example #29
Source File: test_query_enums.py    From graphene-sqlalchemy with MIT License 5 votes vote down vote up
def test_enum_as_argument(session):
    add_test_data(session)

    class PetType(SQLAlchemyObjectType):
        class Meta:
            model = Pet

    class Query(graphene.ObjectType):
        pet = graphene.Field(
            PetType,
            kind=graphene.Argument(PetType.enum_for_field('pet_kind')))

        def resolve_pet(self, info, kind=None):
            query = session.query(Pet)
            if kind:
                query = query.filter(Pet.pet_kind == kind)
            return query.first()

    query = """
        query PetQuery($kind: PetKind) {
          pet(kind: $kind) {
            name,
            petKind
            hairKind
          }
        }
    """

    schema = graphene.Schema(query=Query)
    result = schema.execute(query, variables={"kind": "CAT"})
    assert not result.errors
    expected = {"pet": {"name": "Garfield", "petKind": "CAT", "hairKind": "SHORT"}}
    assert result.data == expected
    result = schema.execute(query, variables={"kind": "DOG"})
    assert not result.errors
    expected = {"pet": {"name": "Lassie", "petKind": "DOG", "hairKind": "LONG"}}
    result = to_std_dicts(result.data)
    assert result == expected 
Example #30
Source File: test_query_enums.py    From graphene-sqlalchemy with MIT License 5 votes vote down vote up
def test_query_more_enums(session):
    add_test_data(session)

    class PetType(SQLAlchemyObjectType):
        class Meta:
            model = Pet

    class Query(graphene.ObjectType):
        pet = graphene.Field(PetType)

        def resolve_pet(self, _info):
            return session.query(Pet).first()

    query = """
        query PetQuery {
          pet {
            name,
            petKind
            hairKind
          }
        }
    """
    expected = {"pet": {"name": "Garfield", "petKind": "CAT", "hairKind": "SHORT"}}
    schema = graphene.Schema(query=Query)
    result = schema.execute(query)
    assert not result.errors
    result = to_std_dicts(result.data)
    assert result == expected