Python graphene.InputField() Examples

The following are 14 code examples of graphene.InputField(). 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: inputobjecttype.py    From graphene with MIT License 6 votes vote down vote up
def __init_subclass_with_meta__(cls, container=None, _meta=None, **options):
        if not _meta:
            _meta = InputObjectTypeOptions(cls)

        fields = {}
        for base in reversed(cls.__mro__):
            fields.update(yank_fields_from_attrs(base.__dict__, _as=InputField))

        if _meta.fields:
            _meta.fields.update(fields)
        else:
            _meta.fields = fields
        if container is None:
            container = type(cls.__name__, (InputObjectTypeContainer, cls), {})
        _meta.container = container
        super(InputObjectType, cls).__init_subclass_with_meta__(_meta=_meta, **options) 
Example #2
Source File: inputfield.py    From graphene with MIT License 6 votes vote down vote up
def __init__(
        self,
        type_,
        name=None,
        default_value=Undefined,
        deprecation_reason=None,
        description=None,
        required=False,
        _creation_counter=None,
        **extra_args
    ):
        super(InputField, self).__init__(_creation_counter=_creation_counter)
        self.name = name
        if required:
            type_ = NonNull(type_)
        self._type = type_
        self.deprecation_reason = deprecation_reason
        self.default_value = default_value
        self.description = description 
Example #3
Source File: test_filter_set.py    From graphene-sqlalchemy-filter with MIT License 6 votes vote down vote up
def test_conjunction_filter_field_types():
    filter_fields = deepcopy(UserFilter._meta.fields)

    for op in [UserFilter.AND, UserFilter.OR]:
        assert op in filter_fields
        assert isinstance(filter_fields[op], graphene.InputField)

        input_field = filter_fields[op].type
        assert isinstance(input_field, graphene.List)

        input_field_of_type = input_field.of_type
        assert isinstance(input_field_of_type, graphene.NonNull)

        non_null_input_field_of_type = input_field_of_type.of_type
        assert non_null_input_field_of_type is UserFilter

        del filter_fields[op] 
Example #4
Source File: mutation.py    From graphene-django with MIT License 6 votes vote down vote up
def __init_subclass_with_meta__(
        cls, form_class=None, only_fields=(), exclude_fields=(), **options
    ):

        if not form_class:
            raise Exception("form_class is required for DjangoFormMutation")

        form = form_class()
        input_fields = fields_for_form(form, only_fields, exclude_fields)
        output_fields = fields_for_form(form, only_fields, exclude_fields)

        _meta = DjangoFormMutationOptions(cls)
        _meta.form_class = form_class
        _meta.fields = yank_fields_from_attrs(output_fields, _as=Field)

        input_fields = yank_fields_from_attrs(input_fields, _as=InputField)
        super(DjangoFormMutation, cls).__init_subclass_with_meta__(
            _meta=_meta, input_fields=input_fields, **options
        ) 
Example #5
Source File: inputobjecttype.py    From graphene 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 #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: test_filter_set.py    From graphene-sqlalchemy-filter with MIT License 5 votes vote down vote up
def test_custom_filter_field_type():
    filter_fields = deepcopy(UserFilter._meta.fields)

    assert 'is_admin' in filter_fields
    is_rich = filter_fields['is_admin']
    assert isinstance(is_rich, graphene.InputField)
    assert is_rich.type is graphene.Boolean
    del filter_fields['is_admin'] 
Example #8
Source File: test_filter_set.py    From graphene-sqlalchemy-filter with MIT License 5 votes vote down vote up
def test_default_filter_field_types():
    filter_fields = deepcopy(UserFilter._meta.fields)

    for model_field, operators in USER_FILTER_FIELDS.items():
        for op in operators:
            field = model_field
            graphql_op = UserFilter.GRAPHQL_EXPRESSION_NAMES[op]
            if graphql_op:
                field += filters.DELIMITER + graphql_op

            assert field in filter_fields, 'Field not found: ' + field
            assert isinstance(filter_fields[field], graphene.InputField)
            del filter_fields[field] 
Example #9
Source File: relay.py    From django-graphql-jwt with MIT License 5 votes vote down vote up
def Field(cls, *args, **kwargs):
        cls._meta.arguments['input']._meta.fields.update({
            get_user_model().USERNAME_FIELD:
            graphene.InputField(graphene.String, required=True),
            'password': graphene.InputField(graphene.String, required=True),
        })
        return super().Field(*args, **kwargs) 
Example #10
Source File: utils.py    From graphene-django-plus with MIT License 5 votes vote down vote up
def _get_input_attrs(object_type):
    new = {}

    for attr, value in object_type.__dict__.items():
        if not isinstance(value, (MountedType, UnmountedType)):
            continue

        if isinstance(value, Structure) and issubclass(value.of_type, graphene.ObjectType):
            value = type(value)(_input_registry[value.of_type])
        elif isinstance(value, graphene.ObjectType):
            value = _input_registry[value.of_type]

        new[attr] = value

    return yank_fields_from_attrs(new, _as=graphene.InputField) 
Example #11
Source File: mutations.py    From graphene-django-plus with MIT License 5 votes vote down vote up
def __init_subclass_with_meta__(cls, model=None,
                                    object_permissions=None,
                                    object_permissions_any=True,
                                    return_field_name=None,
                                    required_fields=None,
                                    exclude_fields=None, only_fields=None,
                                    _meta=None, **kwargs):
        if not model:  # pragma: no cover
            raise ImproperlyConfigured("model is required for ModelMutation")
        if not _meta:
            _meta = ModelMutationOptions(cls)

        exclude_fields = exclude_fields or []
        only_fields = only_fields or []
        if not return_field_name:
            return_field_name = _get_model_name(model)

        input_fields = _get_fields(model, only_fields, exclude_fields,
                                   required_fields)
        input_fields = yank_fields_from_attrs(input_fields, _as=graphene.InputField)

        fields = _get_output_fields(model, return_field_name)

        _meta.model = model
        _meta.object_permissions = object_permissions or []
        _meta.object_permissions_any = object_permissions_any
        _meta.return_field_name = return_field_name
        _meta.exclude_fields = exclude_fields
        _meta.only_fields = only_fields
        _meta.required_fields = required_fields

        super().__init_subclass_with_meta__(
            _meta=_meta,
            input_fields=input_fields,
            **kwargs,
        )

        cls._meta.fields.update(fields) 
Example #12
Source File: filters.py    From graphene-sqlalchemy-filter with MIT License 4 votes vote down vote up
def __init_subclass_with_meta__(
        cls, model=None, fields=None, _meta=None, **options
    ):
        if model is None and fields:
            raise AttributeError('Model not specified')

        if not _meta:
            _meta = FilterSetOptions(cls)

        cls.model = model
        _meta.model = model

        extra_expressions = {}
        extra_allowed_filters = {}
        for klass in reversed(cls.__mro__):
            with contextlib.suppress(AttributeError):
                for key, expr in klass.EXTRA_EXPRESSIONS.items():
                    extra_expressions[key] = expr

            with contextlib.suppress(AttributeError):
                for key, exprs in klass.EXTRA_ALLOWED_FILTERS.items():
                    extra_allowed_filters[key] = exprs

        if extra_expressions or extra_allowed_filters:
            cls._register_extra(extra_expressions, extra_allowed_filters)

        filters_fields = {}
        if model is not None:
            # Add default filter objects.
            filters_fields = cls._generate_default_filters(model, fields)

        for op in [cls.AND, cls.OR, cls.NOT]:
            doc = cls.DESCRIPTIONS.get(op)
            graphql_name = cls.GRAPHQL_EXPRESSION_NAMES[op]
            filters_fields[graphql_name] = graphene.InputField(
                cls.FILTER_OBJECT_TYPES[op](cls, False, doc), description=doc
            )

        if not _meta.fields:
            _meta.fields = {}

        _meta.fields.update(filters_fields)

        default_filter_keys = set(filters_fields.keys())

        # Add custom filter objects.
        super().__init_subclass_with_meta__(_meta=_meta, **options)

        # Save set of custom filter names.
        cls._custom_filters = set()
        meta_fields = set(_meta.fields.keys())
        if meta_fields:
            cls._custom_filters = meta_fields.difference(default_filter_keys) 
Example #13
Source File: filters.py    From graphene-sqlalchemy-filter with MIT License 4 votes vote down vote up
def _generate_default_filters(
        cls, model, field_filters: 'Dict[str, Union[Iterable[str], Any]]'
    ) -> dict:
        """
        Generate GraphQL fields from SQLAlchemy model columns.

        Args:
            model: SQLAlchemy model.
            field_filters: Filters for fields.

        Returns:
            GraphQL fields dictionary:
            field name (key) - field instance (value).

        """
        graphql_filters = {}
        filters_map = cls.ALLOWED_FILTERS
        model_fields = cls._get_model_fields_data(model, field_filters.keys())

        for field_name, field_object in model_fields.items():
            column_type = field_object['type']

            expressions = field_filters[field_name]
            if expressions == cls.ALL:
                type_class = column_type.__class__
                try:
                    expressions = filters_map[type_class].copy()
                except KeyError:
                    for type_, exprs in filters_map.items():
                        if issubclass(type_class, type_):
                            expressions = exprs.copy()
                            break
                    else:
                        raise KeyError(
                            'Unsupported column type. '
                            'Hint: use EXTRA_ALLOWED_FILTERS.'
                        )

                if field_object['nullable']:
                    expressions.append(cls.IS_NULL)

            field_type = convert_sqlalchemy_type(
                column_type, field_object['column']
            )

            fields = cls._generate_filter_fields(
                expressions, field_name, field_type, field_object['nullable']
            )
            for name, field in fields.items():
                graphql_filters[name] = get_field_as(
                    field, graphene.InputField
                )

        return graphql_filters 
Example #14
Source File: mutation.py    From graphene-django with MIT License 4 votes vote down vote up
def __init_subclass_with_meta__(
        cls,
        form_class=None,
        model=None,
        return_field_name=None,
        only_fields=(),
        exclude_fields=(),
        **options
    ):

        if not form_class:
            raise Exception("form_class is required for DjangoModelFormMutation")

        if not model:
            model = form_class._meta.model

        if not model:
            raise Exception("model is required for DjangoModelFormMutation")

        form = form_class()
        input_fields = fields_for_form(form, only_fields, exclude_fields)
        if "id" not in exclude_fields:
            input_fields["id"] = graphene.ID()

        registry = get_global_registry()
        model_type = registry.get_type_for_model(model)
        if not model_type:
            raise Exception("No type registered for model: {}".format(model.__name__))

        if not return_field_name:
            model_name = model.__name__
            return_field_name = model_name[:1].lower() + model_name[1:]

        output_fields = OrderedDict()
        output_fields[return_field_name] = graphene.Field(model_type)

        _meta = DjangoModelDjangoFormMutationOptions(cls)
        _meta.form_class = form_class
        _meta.model = model
        _meta.return_field_name = return_field_name
        _meta.fields = yank_fields_from_attrs(output_fields, _as=Field)

        input_fields = yank_fields_from_attrs(input_fields, _as=InputField)
        super(DjangoModelFormMutation, cls).__init_subclass_with_meta__(
            _meta=_meta, input_fields=input_fields, **options
        )