Python graphene.Argument() Examples

The following are 15 code examples of graphene.Argument(). 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: fields.py    From graphene-gae with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, ndb_key_prop, graphql_type_name, *args, **kwargs):
        self.__ndb_key_prop = ndb_key_prop
        self.__graphql_type_name = graphql_type_name
        is_repeated = ndb_key_prop._repeated
        is_required = ndb_key_prop._required

        _type = String
        if is_repeated:
            _type = List(_type)

        if is_required:
            _type = NonNull(_type)

        kwargs['args'] = {
            'ndb': Argument(Boolean, False, description="Return an NDB id (key.id()) instead of a GraphQL global id")
        }

        super(NdbKeyStringField, self).__init__(_type, *args, **kwargs) 
Example #2
Source File: test_graphql_handler.py    From graphene-gae with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_reports_argument_validation_errors(self):
        for method in (self.get, self.post):
            response = method('/graphql', expect_errors=True, params=dict(
                query='''
                    query helloYou { greet(who: 123), ...shared }
                    query helloWorld { greet(who: "World"), ...shared }
                    query helloDolly { greet(who: "Dolly"), ...shared }
                    fragment shared on Query {
                        shared: greet(who: "Everyone")
                    }
                ''',
                operation_name='helloYou'
            ))

            self.assertEqual(response.status_int, 400)

            response_dict = json.loads(response.body)
            self.assertEqual(response_dict["errors"][0]["message"], "Argument \"who\" has invalid value 123.\nExpected type \"String\", found 123.") 
Example #3
Source File: utils.py    From graphene-sqlalchemy with MIT License 6 votes vote down vote up
def sort_argument_for_model(cls, has_default=True):
    """Get a Graphene Argument for sorting the given model class.

    This is deprecated, please use object_type.sort_argument() instead.
    """
    warnings.warn(
        "sort_argument_for_model() is deprecated;"
        " use object_type.sort_argument() instead.",
        DeprecationWarning,
        stacklevel=2,
    )

    from graphene import Argument, List
    from .enums import sort_enum_for_object_type

    enum = sort_enum_for_object_type(
        _deprecated_object_type_for_model(cls, None),
        get_symbol_name=_deprecated_default_symbol_name,
    )
    if not has_default:
        enum.default = None

    return Argument(List(enum), default_value=enum.default) 
Example #4
Source File: fields.py    From graphene-mongo with MIT License 6 votes vote down vote up
def filter_args(self):
        filter_args = dict()
        if self._type._meta.filter_fields:
            for field, filter_collection in self._type._meta.filter_fields.items():
                for each in filter_collection:
                    filter_type = getattr(
                        graphene,
                        str(self._type._meta.fields[field].type).replace("!", ""),
                    )

                    # handle special cases
                    advanced_filter_types = {
                        "in": graphene.List(filter_type),
                        "nin": graphene.List(filter_type),
                        "all": graphene.List(filter_type),
                    }

                    filter_type = advanced_filter_types.get(each, filter_type)
                    filter_args[field + "__" + each] = graphene.Argument(
                        type=filter_type
                    )

        return filter_args 
Example #5
Source File: fields.py    From graphene-django-extras with MIT License 5 votes vote down vote up
def __init__(
        self,
        _type,
        fields=None,
        extra_filter_meta=None,
        filterset_class=None,
        *args,
        **kwargs,
    ):

        if DJANGO_FILTER_INSTALLED:
            _fields = _type._meta.filter_fields
            _model = _type._meta.model

            self.fields = fields or _fields

            meta = dict(model=_model, fields=self.fields)
            if extra_filter_meta:
                meta.update(extra_filter_meta)

            filterset_class = filterset_class or _type._meta.filterset_class
            self.filterset_class = get_filterset_class(filterset_class, **meta)
            self.filtering_args = get_filtering_args_from_filterset(
                self.filterset_class, _type
            )
            kwargs.setdefault("args", {})
            kwargs["args"].update(self.filtering_args)

            if "id" not in kwargs["args"].keys():
                id_description = "Django object unique identification field"
                self.filtering_args.update(
                    {"id": Argument(ID, description=id_description)}
                )
                kwargs["args"].update({"id": Argument(ID, description=id_description)})

        if not kwargs.get("description", None):
            kwargs["description"] = "{} list".format(_type._meta.model.__name__)

        super(DjangoListObjectField, self).__init__(_type, *args, **kwargs) 
Example #6
Source File: types.py    From graphene-django-extras with MIT License 5 votes vote down vote up
def get_type(cls):
        """
        This function is called when the unmounted type (InputObjectType instance)
        is mounted (as a Field, InputField or Argument)
        """
        return cls 
Example #7
Source File: dauphin_registry.py    From dagster with Apache License 2.0 5 votes vote down vote up
def create_registry_argument(registry):
    class Argument(graphene.Argument):
        def __init__(self, dauphin_type, *args, **kwargs):
            super(Argument, self).__init__(get_type_fn(registry, dauphin_type), *args, **kwargs)

    return Argument 
Example #8
Source File: test_sort_enums.py    From graphene-sqlalchemy with MIT License 5 votes vote down vote up
def test_sort_argument():
    class PetType(SQLAlchemyObjectType):
        class Meta:
            model = Pet

    sort_arg = PetType.sort_argument()
    assert isinstance(sort_arg, Argument)

    assert isinstance(sort_arg.type, List)
    sort_enum = sort_arg.type._of_type
    assert isinstance(sort_enum, type(Enum))
    assert sort_enum._meta.name == "PetTypeSortEnum"
    assert list(sort_enum._meta.enum.__members__) == [
        "ID_ASC",
        "ID_DESC",
        "NAME_ASC",
        "NAME_DESC",
        "PET_KIND_ASC",
        "PET_KIND_DESC",
        "HAIR_KIND_ASC",
        "HAIR_KIND_DESC",
        "REPORTER_ID_ASC",
        "REPORTER_ID_DESC",
    ]
    assert str(sort_enum.ID_ASC.value.value) == "pets.id ASC"
    assert str(sort_enum.ID_DESC.value.value) == "pets.id DESC"
    assert str(sort_enum.HAIR_KIND_ASC.value.value) == "pets.hair_kind ASC"
    assert str(sort_enum.HAIR_KIND_DESC.value.value) == "pets.hair_kind DESC"

    assert sort_arg.default_value == ["ID_ASC"]
    assert str(sort_enum.ID_ASC.value.value) == "pets.id ASC" 
Example #9
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 #10
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 #11
Source File: test_fields.py    From graphene-django with MIT License 5 votes vote down vote up
def test_filterset_descriptions():
    class ArticleIdFilter(django_filters.FilterSet):
        class Meta:
            model = Article
            fields = ["id"]

        max_time = django_filters.NumberFilter(
            method="filter_max_time", label="The maximum time"
        )

    field = DjangoFilterConnectionField(ArticleNode, filterset_class=ArticleIdFilter)
    max_time = field.args["max_time"]
    assert isinstance(max_time, Argument)
    assert max_time.type == Float
    assert max_time.description == "The maximum time" 
Example #12
Source File: fields.py    From graphene-django-extras with MIT License 4 votes vote down vote up
def __init__(
        self,
        _type,
        fields=None,
        extra_filter_meta=None,
        filterset_class=None,
        *args,
        **kwargs,
    ):

        if DJANGO_FILTER_INSTALLED:
            _fields = _type._meta.filter_fields
            _model = _type._meta.model

            self.fields = fields or _fields
            meta = dict(model=_model, fields=self.fields)
            if extra_filter_meta:
                meta.update(extra_filter_meta)
            filterset_class = filterset_class or _type._meta.filterset_class
            self.filterset_class = get_filterset_class(filterset_class, **meta)
            self.filtering_args = get_filtering_args_from_filterset(
                self.filterset_class, _type
            )
            kwargs.setdefault("args", {})
            kwargs["args"].update(self.filtering_args)

            if "id" not in kwargs["args"].keys():
                self.filtering_args.update(
                    {
                        "id": Argument(
                            ID, description="Django object unique identification field"
                        )
                    }
                )
                kwargs["args"].update(
                    {
                        "id": Argument(
                            ID, description="Django object unique identification field"
                        )
                    }
                )

        if not kwargs.get("description", None):
            kwargs["description"] = "{} list".format(_type._meta.model.__name__)

        super(DjangoFilterListField, self).__init__(List(_type), *args, **kwargs) 
Example #13
Source File: fields.py    From graphene-django-extras with MIT License 4 votes vote down vote up
def __init__(
        self,
        _type,
        pagination=None,
        fields=None,
        extra_filter_meta=None,
        filterset_class=None,
        *args,
        **kwargs,
    ):

        _fields = _type._meta.filter_fields
        _model = _type._meta.model

        self.fields = fields or _fields
        meta = dict(model=_model, fields=self.fields)
        if extra_filter_meta:
            meta.update(extra_filter_meta)

        filterset_class = filterset_class or _type._meta.filterset_class
        self.filterset_class = get_filterset_class(filterset_class, **meta)
        self.filtering_args = get_filtering_args_from_filterset(
            self.filterset_class, _type
        )
        kwargs.setdefault("args", {})
        kwargs["args"].update(self.filtering_args)

        if "id" not in kwargs["args"].keys():
            self.filtering_args.update(
                {
                    "id": Argument(
                        ID, description="Django object unique identification field"
                    )
                }
            )
            kwargs["args"].update(
                {
                    "id": Argument(
                        ID, description="Django object unique identification field"
                    )
                }
            )

        pagination = pagination or graphql_api_settings.DEFAULT_PAGINATION_CLASS()

        if pagination is not None:
            assert isinstance(pagination, BaseDjangoGraphqlPagination), (
                'You need to pass a valid DjangoGraphqlPagination in DjangoFilterPaginateListField, received "{}".'
            ).format(pagination)

            pagination_kwargs = pagination.to_graphql_fields()

            self.pagination = pagination
            kwargs.update(**pagination_kwargs)

        if not kwargs.get("description", None):
            kwargs["description"] = "{} list".format(_type._meta.model.__name__)

        super(DjangoFilterPaginateListField, self).__init__(
            List(_type), *args, **kwargs
        ) 
Example #14
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 #15
Source File: enums.py    From graphene-sqlalchemy with MIT License 4 votes vote down vote up
def sort_argument_for_object_type(
    obj_type,
    enum_name=None,
    only_fields=None,
    only_indexed=None,
    get_symbol_name=None,
    has_default=True,
):
    """"Returns Graphene Argument for sorting the given SQLAlchemyObjectType.

    Parameters
    - obj_type : SQLAlchemyObjectType
        The object type for which the sort Argument shall be generated.
    - enum_name : str, optional, default None
        Name to use for the sort Enum.
        If not provided, it will be set to the object type name + 'SortEnum'
    - only_fields : sequence, optional, default None
        If this is set, only fields from this sequence will be considered.
    - only_indexed : bool, optional, default False
        If this is set, only indexed columns will be considered.
    - get_symbol_name : function, optional, default None
        Function which takes the column name and a boolean indicating
        if the sort direction is ascending, and returns the symbol name
        for the current column and sort direction. If no such function
        is passed, a default function will be used that creates the symbols
        'foo_asc' and 'foo_desc' for a column with the name 'foo'.
    - has_default : bool, optional, default True
        If this is set to False, no sorting will happen when this argument is not
        passed. Otherwise results will be sortied by the primary key(s) of the model.

    Returns
    - Enum
        A Graphene Argument that accepts a list of sorting directions for the model.
    """
    enum = sort_enum_for_object_type(
        obj_type,
        enum_name,
        only_fields=only_fields,
        only_indexed=only_indexed,
        get_symbol_name=get_symbol_name,
    )
    if not has_default:
        enum.default = None

    return Argument(List(enum), default_value=enum.default)