Python graphene.List() Examples
The following are 30
code examples of graphene.List().
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: ql.py From flask-graphql-example with MIT License | 6 votes |
def mutate(cls, _, info, __): logger.debug("agrs %s", info) post_schema = t.Dict({ 'title': t.String(min_length=2), 'user_id': t.String(min_length=2), 'content': t.String(min_length=2), t.Key('tags', optional=True): t.List(t.String, min_length=1), }) post_data = post_schema.check(info) user_id = post_data.pop('user_id') user = User.objects.get_or_404(id=user_id) post = Post(author=user, **post_data) post.save() return cls(post=construct(PostField, post))
Example #2
Source File: fields.py From graphene-gae with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #3
Source File: base.py From backend.ai-manager with GNU Lesser General Public License v3.0 | 6 votes |
def batch_multiresult( context: Mapping[str, Any], conn: SAConnection, query: sa.sql.Select, obj_type: Type[_GenericSQLBasedGQLObject], key_list: Iterable[_Key], key_getter: Callable[[RowProxy], _Key], ) -> Sequence[Sequence[_GenericSQLBasedGQLObject]]: """ A batched query adaptor for (key -> [item]) resolving patterns. """ objs_per_key: Dict[_Key, List[_GenericSQLBasedGQLObject]] objs_per_key = collections.OrderedDict() for key in key_list: objs_per_key[key] = list() async for row in conn.execute(query): objs_per_key[key_getter(row)].append( obj_type.from_row(context, row) ) return [*objs_per_key.values()]
Example #4
Source File: test_converter.py From graphene-django with MIT License | 6 votes |
def test_should_postgres_array_multiple_convert_list(): field = assert_conversion( ArrayField, graphene.List, ArrayField(models.CharField(max_length=100)) ) assert isinstance(field.type, graphene.NonNull) assert isinstance(field.type.of_type, graphene.List) assert isinstance(field.type.of_type.of_type, graphene.List) assert isinstance(field.type.of_type.of_type.of_type, graphene.NonNull) assert field.type.of_type.of_type.of_type.of_type == graphene.String field = assert_conversion( ArrayField, graphene.List, ArrayField(models.CharField(max_length=100, null=True)), ) assert isinstance(field.type, graphene.NonNull) assert isinstance(field.type.of_type, graphene.List) assert isinstance(field.type.of_type.of_type, graphene.List) assert field.type.of_type.of_type.of_type == graphene.String
Example #5
Source File: converter.py From graphene-gae with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #6
Source File: utils.py From graphene-django-extras with MIT License | 6 votes |
def __init__(self, _type, paginator_instance, *args, **kwargs): kwargs.setdefault("args", {}) self.paginator_instance = paginator_instance kwargs.update(self.paginator_instance.to_graphql_fields()) kwargs.update( { "description": "{} list, paginated by {}".format( _type._meta.model.__name__, paginator_instance.__name__ ) } ) super(GenericPaginationField, self).__init__( graphene.List(_type), *args, **kwargs )
Example #7
Source File: test_types.py From graphene-gae with BSD 3-Clause "New" or "Revised" License | 6 votes |
def testQuery_onlyFields(self): Article(headline="h1", summary="s1").put() class ArticleType(NdbObjectType): class Meta: model = Article only_fields = ['headline'] class QueryType(graphene.ObjectType): articles = graphene.List(ArticleType) def resolve_articles(self, info): return Article.query() schema = graphene.Schema(query=QueryType) query = ''' query ArticlesQuery { articles { headline } } ''' result = schema.execute(query) self.assertIsNotNone(result.data) self.assertEqual(result.data['articles'][0]['headline'], 'h1') query = ''' query ArticlesQuery { articles { headline, summary } } ''' result = schema.execute(query) self.assertIsNotNone(result.errors) self.assertTrue('Cannot query field "summary"' in result.errors[0].message)
Example #8
Source File: test_converter.py From graphene-django with MIT License | 6 votes |
def test_should_manytomany_convert_connectionorlist_list(): class A(DjangoObjectType): class Meta: model = Reporter graphene_field = convert_django_field( Reporter._meta.local_many_to_many[0], A._meta.registry ) assert isinstance(graphene_field, graphene.Dynamic) dynamic_field = graphene_field.get_type() assert isinstance(dynamic_field, graphene.Field) # A NonNull List of NonNull A ([A!]!) # https://github.com/graphql-python/graphene-django/issues/448 assert isinstance(dynamic_field.type, NonNull) assert isinstance(dynamic_field.type.of_type, graphene.List) assert isinstance(dynamic_field.type.of_type.of_type, NonNull) assert dynamic_field.type.of_type.of_type.of_type == A
Example #9
Source File: test_filter_set.py From graphene-sqlalchemy-filter with MIT License | 6 votes |
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 #10
Source File: utils.py From graphene-sqlalchemy with MIT License | 6 votes |
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 #11
Source File: query.py From gigantum-client with MIT License | 6 votes |
def resolve_background_jobs(self, info, **kwargs): """Method to return a all background jobs the system is aware of: Queued, Started, Finished, Failed. Returns: list(JobStatus) """ job_dispatcher = Dispatcher() edges: List[str] = [j.job_key.key_str for j in job_dispatcher.all_jobs] cursors = [base64.b64encode(f"{str(cnt)}".encode('utf-8')) for cnt, x in enumerate(edges)] # Process slicing and cursor args lbc = ListBasedConnection(edges, cursors, kwargs) lbc.apply() edge_objs = [] for edge, cursor in zip(lbc.edges, lbc.cursors): edge_objs.append(JobStatusConnection.Edge(node=JobStatus(edge), cursor=cursor)) return JobStatusConnection(edges=edge_objs, page_info=lbc.page_info)
Example #12
Source File: fields.py From graphene-mongo with MIT License | 6 votes |
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 #13
Source File: test_field_converter.py From graphene-django with MIT License | 5 votes |
def test_should_list_serializer_convert_to_list(): class FooModel(models.Model): pass class ChildSerializer(serializers.ModelSerializer): class Meta: model = FooModel fields = "__all__" class ParentSerializer(serializers.ModelSerializer): child = ChildSerializer(many=True) class Meta: model = FooModel fields = "__all__" converted_type = convert_serializer_field( ParentSerializer().get_fields()["child"], is_input=True ) assert isinstance(converted_type, graphene.List) converted_type = convert_serializer_field( ParentSerializer().get_fields()["child"], is_input=False ) assert isinstance(converted_type, graphene.List) assert converted_type.of_type is None
Example #14
Source File: test_converter.py From graphene-mongo with MIT License | 5 votes |
def test_should_field_convert_list(): assert_conversion( mongoengine.ListField, graphene.List, field=mongoengine.StringField() )
Example #15
Source File: test_converter.py From graphene-mongo with MIT License | 5 votes |
def test_should_list_of_reference_convert_list(): class A(MongoengineObjectType): class Meta: model = Article graphene_field = convert_mongoengine_field( Reporter._fields["articles"], A._meta.registry ) assert isinstance(graphene_field, graphene.List) dynamic_field = graphene_field.get_type() assert dynamic_field._of_type == A
Example #16
Source File: test_converter.py From graphene-mongo with MIT License | 5 votes |
def test_should_list_of_embedded_convert_list(): class E(MongoengineObjectType): class Meta: model = EmbeddedArticle graphene_field = convert_mongoengine_field( Reporter._fields["embedded_articles"], E._meta.registry ) assert isinstance(graphene_field, graphene.List) dynamic_field = graphene_field.get_type() assert dynamic_field._of_type == E
Example #17
Source File: serializer_converter.py From graphene-django with MIT License | 5 votes |
def convert_serializer_field_to_list_of_enum(field): child_type = convert_serializer_field_to_enum(field) return (graphene.List, child_type)
Example #18
Source File: test_field_converter.py From graphene-django with MIT License | 5 votes |
def test_should_multiplechoicefield_convert_to_list_of_enum(): field = assert_conversion( serializers.MultipleChoiceField, graphene.List, choices=[1, 2, 3] ) assert issubclass(field.of_type, graphene.Enum)
Example #19
Source File: converter.py From graphene-mongo with MIT License | 5 votes |
def convert_field_to_list(field, registry=None): base_type = convert_mongoengine_field(field.field, registry=registry) if isinstance(base_type, graphene.Field): return graphene.List( base_type._type, description=get_field_description(field, registry), required=field.required ) if isinstance(base_type, (graphene.Dynamic)): base_type = base_type.get_type() if base_type is None: return base_type = base_type._type if graphene.is_node(base_type): return base_type._meta.connection_field_class(base_type) # Non-relationship field relations = (mongoengine.ReferenceField, mongoengine.EmbeddedDocumentField) if not isinstance(base_type, (graphene.List, graphene.NonNull)) and not isinstance( field.field, relations ): base_type = type(base_type) return graphene.List( base_type, description=get_field_description(field, registry), required=field.required, )
Example #20
Source File: test_fields.py From graphene-django with MIT License | 5 votes |
def test_non_null_type(self): class Reporter(DjangoObjectType): class Meta: model = ReporterModel fields = ("first_name",) list_field = DjangoListField(NonNull(Reporter)) assert isinstance(list_field.type, List) assert isinstance(list_field.type.of_type, NonNull) assert list_field.type.of_type.of_type is Reporter
Example #21
Source File: serializer_converter.py From graphene-django with MIT License | 5 votes |
def convert_serializer_field_to_list(field, is_input=True): child_type = get_graphene_type_from_serializer_field(field.child) return (graphene.List, child_type)
Example #22
Source File: test_converter.py From graphene-mongo with MIT License | 5 votes |
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 #23
Source File: test_converter.py From graphene-mongo with MIT License | 5 votes |
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 #24
Source File: test_converter.py From graphene-mongo with MIT License | 5 votes |
def test_should_point_convert_field(): graphene_type = convert_mongoengine_field(mongoengine.PointField()) assert isinstance(graphene_type, graphene.Field) assert graphene_type.type == advanced_types.PointFieldType assert isinstance(graphene_type.type.type, graphene.String) assert isinstance(graphene_type.type.coordinates, graphene.List)
Example #25
Source File: test_query.py From graphene-mongo with MIT License | 5 votes |
def test_should_custom_kwargs(fixtures): class Query(graphene.ObjectType): editors = graphene.List(types.EditorType, first=graphene.Int()) def resolve_editors(self, *args, **kwargs): editors = models.Editor.objects() if "first" in kwargs: editors = editors[: kwargs["first"]] return list(editors) query = """ query EditorQuery { editors(first: 2) { firstName, lastName } } """ expected = { "editors": [ {"firstName": "Penny", "lastName": "Hardaway"}, {"firstName": "Grant", "lastName": "Hill"}, ] } schema = graphene.Schema(query=Query) result = schema.execute(query) assert not result.errors assert result.data == expected
Example #26
Source File: create_model_schema.py From graphql-over-kafka with MIT License | 5 votes |
def create_model_schema(target_model): """ This function creates a graphql schema that provides a single model """ from nautilus.database import db # create the schema instance schema = graphene.Schema(auto_camelcase=False) # grab the primary key from the model primary_key = target_model.primary_key() primary_key_type = convert_peewee_field(primary_key) # create a graphene object class ModelObjectType(PeeweeObjectType): class Meta: model = target_model pk = Field(primary_key_type, description="The primary key for this object.") @graphene.resolve_only_args def resolve_pk(self): return getattr(self, self.primary_key().name) class Query(graphene.ObjectType): """ the root level query """ all_models = List(ModelObjectType, args=args_for_model(target_model)) @graphene.resolve_only_args def resolve_all_models(self, **args): # filter the model query according to the arguments # print(filter_model(target_model, args)[0].__dict__) return filter_model(target_model, args) # add the query to the schema schema.query = Query return schema
Example #27
Source File: datasetlist.py From gigantum-client with MIT License | 5 votes |
def resolve_local_by_id(self, info, ids): """Method to return graphene Dataset instances based on a list of Global Node IDs Uses the "currently logged in" user Args: ids(list): List of Node IDs for the local datasets to return Returns: list(Dataset) """ return [graphene.Node.get_node_from_global_id(info, x) for x in ids]
Example #28
Source File: labbooklist.py From gigantum-client with MIT License | 5 votes |
def resolve_local_by_id(self, info, ids): """Method to return graphene Labbook instances based on a list of Global Node IDs Uses the "currently logged in" user Args: ids(list): List of Node IDs for the local labbooks to return Returns: list(Labbook) """ return [graphene.Node.get_node_from_global_id(info, x) for x in ids]
Example #29
Source File: object_types.py From flask-unchained with MIT License | 5 votes |
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 #30
Source File: object_types.py From flask-unchained with MIT License | 5 votes |
def _get_list_resolver(list_: graphene.List): def _get_list(self, info, **kwargs): return list_.of_type._meta.model.query.all() return _get_list