Python graphene.ID Examples

The following are 30 code examples of graphene.ID(). 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: mutations.py    From graphene-django-plus with MIT License 6 votes vote down vote up
def perform_mutation(cls, root, info, **data):
        """Perform the mutation.

        Delete the instance from the database given its `id` attribute
        in the input data.
        """
        instance = cls.get_instance(info, data.get('id'))

        db_id = instance.id
        cls.delete(info, instance)

        # After the instance is deleted, set its ID to the original database's
        # ID so that the success response contains ID of the deleted object.
        instance.id = db_id
        return cls(**{cls._meta.return_field_name: instance})


# Compatibility with older versions 
Example #2
Source File: converter.py    From graphene-django with MIT License 5 votes vote down vote up
def convert_form_field_to_id(field):
    return ID(required=field.required) 
Example #3
Source File: query.py    From lutece-backend with GNU General Public License v3.0 5 votes vote down vote up
def resolve_contest_ranking_list(self: None, info: ResolveInfo, pk: graphene.ID()):
        contest = Contest.objects.get(pk=pk)
        privilege = info.context.user.has_perm('contest.view_contest')
        if datetime.now() < contest.settings.start_time and not privilege:
            return ''
        return json.dumps([{
            'status': each.judge_result,
            'createTime': str(each.create_time),
            'team': each.team_name,
            'problemId': each.problem_id,
            'teamApproved': each.team_approved
        } for each in (ContestSubmission.objects.raw(
            '''
                SELECT 
                    submission_ptr_id,
                    contest_contestteam.name as team_name,
                    contest_contestteam.approved as team_approved,
                    submission_submission.create_time as create_time,
                    submission_submission.problem_id as problem_id,
                    submission_submission.result_id as result_id,
                    judge_judgeresult._result as judge_result
                FROM contest_contestsubmission
                LEFT JOIN contest_contestteam ON contest_contestsubmission.team_id = contest_contestteam.id
                LEFT JOIN submission_submission ON contest_contestsubmission.submission_ptr_id = submission_submission.id
                LEFT JOIN judge_judgeresult ON result_id = judge_judgeresult.id
                WHERE contest_contestsubmission.contest_id = (%s) and contest_contestsubmission.team_id IS NOT NULL
            ''',
            (pk,)
        ))]) 
Example #4
Source File: type.py    From lutece-backend with GNU General Public License v3.0 5 votes vote down vote up
def resolve_pk(self, info: ResolveInfo) -> graphene.ID:
        return self.pk 
Example #5
Source File: type.py    From lutece-backend with GNU General Public License v3.0 5 votes vote down vote up
def resolve_pk(self, info: ResolveInfo) -> graphene.ID():
        return self.pk 
Example #6
Source File: type.py    From lutece-backend with GNU General Public License v3.0 5 votes vote down vote up
def resolve_pk(self, info: ResolveInfo) -> graphene.ID():
        return self.pk 
Example #7
Source File: type.py    From lutece-backend with GNU General Public License v3.0 5 votes vote down vote up
def resolve_pk(self, info: ResolveInfo) -> graphene.ID:
        return self.pk 
Example #8
Source File: type.py    From lutece-backend with GNU General Public License v3.0 5 votes vote down vote up
def resolve_pk(self, info: ResolveInfo) -> graphene.ID():
        return self.pk 
Example #9
Source File: mutations.py    From graphene-django-plus with MIT License 5 votes vote down vote up
def clean_input(cls, info, instance, data):
        """Clear and normalize the input data."""
        cleaned_input = {}

        for f_name, f_item in cls.Input._meta.fields.items():
            if f_name not in data:
                continue

            value = data[f_name]

            if value is not None and _is_list_of_ids(f_item):
                # list of IDs field
                instances = cls.get_nodes(value, f_name) if value else []
                cleaned_input[f_name] = instances
            elif value is not None and _is_id_field(f_item):
                # ID field
                instance = cls.get_node(info, value, f_name)
                cleaned_input[f_name] = instance
            elif value is not None and _is_upload_field(f_item):
                # uploaded files
                value = info.context.FILES.get(value)
                cleaned_input[f_name] = value
            else:
                # other fields
                cleaned_input[f_name] = value

        return cleaned_input 
Example #10
Source File: mutations.py    From graphene-django-plus with MIT License 5 votes vote down vote up
def _is_id_field(field):
    return (
        field.type == graphene.ID or
        isinstance(field.type, graphene.NonNull) and
        field.type.of_type == graphene.ID
    ) 
Example #11
Source File: mutations.py    From graphene-django-plus with MIT License 5 votes vote down vote up
def _is_list_of_ids(field):
    return (
        isinstance(field.type, graphene.List) and
        field.type.of_type == graphene.ID
    ) 
Example #12
Source File: fields.py    From graphene-django-extras with MIT License 5 votes vote down vote up
def __init__(self, _type, *args, **kwargs):
        kwargs["id"] = ID(
            required=True, description="Django object unique identification field"
        )

        super(DjangoObjectField, self).__init__(_type, *args, **kwargs) 
Example #13
Source File: test_converter.py    From graphene-django with MIT License 5 votes vote down vote up
def test_should_auto_convert_id():
    assert_conversion(models.AutoField, graphene.ID, primary_key=True) 
Example #14
Source File: query.py    From lutece-backend with GNU General Public License v3.0 5 votes vote down vote up
def resolve_contest_clarification_list(self: None, info: ResolveInfo, pk: graphene.ID(), page: graphene.Int()):
        contest = get_object_or_None(Contest, pk=pk)
        privilege = info.context.user.has_perm('contest.view_contest')
        if datetime.now() < contest.settings.start_time and not privilege:
            return ContestClarificationListType(max_page=1, contest_clarification_list=[])
        if not contest:
            raise GraphQLError('No such contest')
        clarification_list = ContestClarification.objects.filter(contest=contest)
        privilege = info.context.user.has_perm('contest.view_contestclarification')
        if not privilege:
            clarification_list = clarification_list.filter(disable=False)
        clarification_list = clarification_list.order_by('-vote')
        paginator = Paginator(clarification_list, CLARIFICATION_PER_PAGE_COUNT)
        return ContestClarificationListType(max_page=paginator.num_pages,
                                            contest_clarification_list=paginator.get_page(page)) 
Example #15
Source File: converter.py    From graphene-django with MIT License 5 votes vote down vote up
def convert_form_field_to_list(field):
    return List(ID, required=field.required) 
Example #16
Source File: test_converter.py    From graphene-mongo with MIT License 5 votes vote down vote up
def test_should_object_id_convert_id():
    assert_conversion(mongoengine.ObjectIdField, graphene.ID) 
Example #17
Source File: test_converter.py    From graphene-mongo with MIT License 5 votes vote down vote up
def test_should_uuid_convert_id():
    assert_conversion(mongoengine.UUIDField, graphene.ID) 
Example #18
Source File: query.py    From lutece-backend with GNU General Public License v3.0 5 votes vote down vote up
def resolve_contest_team_list(self: None, info: ResolveInfo, pk: graphene.ID()):
        contest = Contest.objects.get(pk=pk)
        return ContestTeam.objects.filter(contest=contest) 
Example #19
Source File: converter.py    From graphene-mongo with MIT License 5 votes vote down vote up
def convert_field_to_id(field, registry=None):
    return graphene.ID(
        description=get_field_description(field, registry), required=field.required
    ) 
Example #20
Source File: object_types.py    From flask-unchained with MIT License 5 votes vote down vote up
def convert_column_to_int_or_id(type, column, registry=None):
    if column.primary_key or column.foreign_keys:
        return graphene.ID(
            description=get_column_doc(column),
            required=not (is_column_nullable(column)),
        )
    else:
        return graphene.Int(
            description=get_column_doc(column),
            required=not (is_column_nullable(column)),
        ) 
Example #21
Source File: query.py    From lutece-backend with GNU General Public License v3.0 5 votes vote down vote up
def resolve_related_contest_team_list(self: None, info: ResolveInfo, pk: graphene.ID()):
        contest = Contest.objects.get(pk=pk)
        return map(lambda each: each.contest_team,
                   ContestTeamMember.objects.filter(contest_team__contest=contest, user=info.context.user)) 
Example #22
Source File: converter.py    From graphql-pynamodb with MIT License 5 votes vote down vote up
def convert_column_to_float_or_id(type, attribute, registry=None):
    if attribute.is_hash_key:
        return ID(description=attribute.attr_name, required=not attribute.null)

    return Float(description=attribute.attr_name, required=not attribute.null) 
Example #23
Source File: converter.py    From graphql-pynamodb with MIT License 5 votes vote down vote up
def convert_column_to_string(type, attribute, registry=None):
    if attribute.is_hash_key:
        return ID(description=attribute.attr_name, required=not attribute.null)

    return String(description=getattr(attribute, 'attr_name'),
                  required=not (getattr(attribute, 'null', True))) 
Example #24
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 #25
Source File: query.py    From lutece-backend with GNU General Public License v3.0 5 votes vote down vote up
def resolve_contest_team(self: None, info: ResolveInfo, pk: graphene.ID()):
        return ContestTeam.objects.get(pk=pk) 
Example #26
Source File: serializers.py    From caluma with GNU General Public License v3.0 5 votes vote down vote up
def convert_serializer_primary_key_related_field(field):
    return (graphene.List, graphene.ID) 
Example #27
Source File: mutations.py    From graphene-django-plus with MIT License 4 votes vote down vote up
def _get_fields(model, only_fields, exclude_fields, required_fields):
    fields = [
        (field.name, field)
        for field in sorted(list(model._meta.fields + model._meta.many_to_many))
    ]

    ret = collections.OrderedDict()
    for name, field in fields:
        if ((only_fields and name not in only_fields) or
                name in exclude_fields or
                str(name).endswith('+') or
                name in ['created_at', 'updated_at', 'archived_at']):
            continue

        if name == 'id':
            ret[name] = graphene.ID(
                description="The ID of the object.",
            )
        elif isinstance(field, models.FileField):
            ret[name] = UploadType(
                description=field.help_text,
                required=not field.null,
            )
        elif isinstance(field, models.BooleanField):
            ret[name] = graphene.Boolean(
                description=field.help_text,
                required=not field.null and not field.blank,
            )
        elif isinstance(field, (models.ForeignKey, models.OneToOneField)):
            ret[name] = graphene.ID(
                description=field.help_text,
                required=not field.null,
            )
        elif isinstance(field, models.ManyToManyField):
            ret[name] = graphene.List(
                graphene.ID,
                description=field.help_text,
                required=not field.null,
            )
        else:
            ret[name] = convert_django_field_with_choices(field, _registry)

        if required_fields is not None:
            ret[name].kwargs['required'] = name in required_fields

    return ret 
Example #28
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
        ) 
Example #29
Source File: test_mutation.py    From graphene-mongo with MIT License 4 votes vote down vote up
def test_should_update(fixtures):
    class UpdateEditor(graphene.Mutation):
        class Arguments:
            id = graphene.ID()
            first_name = graphene.String()

        editor = graphene.Field(EditorNode)

        def mutate(self, info, id, first_name):
            editor = Editor.objects.get(id=id)
            editor.first_name = first_name
            editor.save()
            return UpdateEditor(editor=editor)

    class Query(graphene.ObjectType):

        node = Node.Field()

    class Mutation(graphene.ObjectType):

        update_editor = UpdateEditor.Field()

    query = """
        mutation EditorUpdater {
            updateEditor(
                id: "1"
                firstName: "Tony"
            ) {
                editor {
                    firstName
                }
            }
        }
    """
    expected = {"updateEditor": {"editor": {"firstName": "Tony"}}}
    schema = graphene.Schema(query=Query, mutation=Mutation)
    result = schema.execute(query)
    # print(result.data)
    assert not result.errors
    assert result.data == expected 
Example #30
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)