예제 #1
0
 def __init_subclass_with_meta__(cls,
                                 model_mudule,
                                 exclude_models=[],
                                 _meta=None,
                                 **options):
     if not _meta:
         _meta = ObjectTypeOptions(cls)
     fields = OrderedDict()
     fields["node"] = graphene.relay.Node.Field()
     for model_name in dir(model_mudule):
         model_obj = getattr(model_mudule, model_name)
         if isinstance(model_obj, DefaultMeta):
             fields.update({
                 model_name.lower():
                 graphene.relay.Node.Field(
                     SQLAlchemyObjectTypes().get(model_obj)),
                 "%s_list" % model_name.lower():
                 model_connection(model_obj),
             })
     if _meta.fields:
         _meta.fields.update(fields)
     else:
         _meta.fields = fields
     return super(QueryObjectType,
                  cls).__init_subclass_with_meta__(_meta=_meta, **options)
예제 #2
0
 def __init_subclass_with_meta__(cls, declarative_base, session, include_object=None, _meta=None, **options):
     if include_object is None:
         include_object = []
     if not _meta:
         _meta = ObjectTypeOptions(cls)
     fields = OrderedDict()
     include_object_names = list()
     for obj in include_object:
         action = "update"
         if obj._meta.create is True:
             action = "create"
         if obj._meta.delete is True:
             action = "delete"
         name = "%s%s" % (action, obj._meta.model.__name__)
         include_object_names.append(name)
         fields[name] = obj.Field()
     models = [cls for cls in declarative_base._decl_class_registry.values() if
               isinstance(cls, type) and issubclass(cls, declarative_base)]
     for model_obj in models:
         model_name = model_obj.__name__
         # if isinstance(model_obj, DefaultMeta):
         if "create%s" % model_name not in include_object_names:
             fields.update({"create%s" % model_name: model_create(model_obj, session).Field()})
         if "update%s" % model_name not in include_object_names:
             fields.update({"update%s" % model_name: model_update(model_obj, session).Field()})
         if "delete%s" % model_name not in include_object_names:
             fields.update({"delete%s" % model_name: model_delete(model_obj, session).Field()})
     if _meta.fields:
         _meta.fields.update(fields)
     else:
         _meta.fields = fields
     return super(MutationObjectType, cls).__init_subclass_with_meta__(_meta=_meta, **options)
예제 #3
0
 def __init_subclass_with_meta__(cls, model_mudule, include_object=[], _meta=None, **options):
     if not _meta:
         _meta = ObjectTypeOptions(cls)
     fields = OrderedDict()
     include_object_names = list()
     for obj in include_object:
         action = "update"
         if obj._meta.create is True:
             action = "create"
         if obj._meta.delete is True:
             action = "delete"
         name = "%s%s" % (action, obj._meta.model.__name__)
         include_object_names.append(name)
         fields[name] = obj.Field()
     for model_name in dir(model_mudule):
         model_obj = getattr(model_mudule, model_name)
         if isinstance(model_obj, DefaultMeta):
             if "create%s" % model_name not in include_object_names:
                 fields.update({"create%s" % model_name: model_create(model_obj).Field()})
             if "update%s" % model_name not in include_object_names:
                 fields.update({"update%s" % model_name: model_update(model_obj).Field()})
             if "delete%s" % model_name not in include_object_names:
                 fields.update({"delete%s" % model_name: model_delete(model_obj).Field()})
     if _meta.fields:
         _meta.fields.update(fields)
     else:
         _meta.fields = fields
     return super(MutationObjectType, cls).__init_subclass_with_meta__(_meta=_meta, **options)
예제 #4
0
    def __init_subclass_with_meta__(
            cls,
            declarative_base: DeclarativeMeta,
            exclude_models: List[str],
            base_filter_class=FilterSet,
            custom_connection=CustomConnection,
            custom_connection_field=CustomConnectionField,
            custom_schemas_path: str = None,
            custom_filters_path: str = None,
            _meta=None,
            **options):
        logging.info("Generate auto query...")
        if not _meta:
            _meta = ObjectTypeOptions(cls)
        init_custom_connection_field(
            custom_connection_field,
            declarative_base,
            custom_filters_path,
            exclude_models,
            base_filter_class,
        )
        fields = OrderedDict()
        fields["node"] = graphene.relay.Node.Field()
        for model in custom_connection_field.filters:
            logging.debug("Generate fields for {}".format(model.__name__))
            node = node_factory(custom_connection_field, model,
                                custom_schemas_path)
            connection = connections_factory(node, custom_connection)
            query_name = "%s_list" % inflection.underscore(model.__name__)
            fields.update({
                inflection.underscore(model.__name__):
                graphene.relay.Node.Field(node),
                query_name:
                custom_connection_field(
                    connection,
                    limit=graphene.types.Int(),
                    offset=graphene.types.Int(),
                ),
            })

        if _meta.fields:
            _meta.fields.update(fields)
        else:
            _meta.fields = fields
        logging.info("Generate auto query done")
        return super(QueryObjectType,
                     cls).__init_subclass_with_meta__(_meta=_meta, **options)
예제 #5
0
 def __init_subclass_with_meta__(
         cls, declarative_base, exclude_models=None, _meta=None, **options
 ):
     """
     :param declarative_base: sqlalchemy's base
     :param exclude_models: exclude models
     :param _meta:
     :param options:
     :return:
     """
     if exclude_models is None:
         exclude_models = []
     if not _meta:
         _meta = ObjectTypeOptions(cls)
     fields = OrderedDict()
     fields["node"] = graphene.relay.Node.Field()
     if not isinstance(declarative_base, list):
         declarative_base = [declarative_base]
     for base in declarative_base:  # declarative_base can be mutil
         for model in base.registry.mappers:
             model_obj = model.class_
             if model_obj.__name__ in exclude_models:
                 continue
             fields.update(
                 {
                     decapitalize(model_obj.__name__): graphene.relay.Node.Field(
                         SQLAlchemyObjectTypes().get(model_obj)
                     ),
                     "%s_list" % decapitalize(model_obj.__name__): model_connection(model_obj),
                 }
             )
     if _meta.fields:
         _meta.fields.update(fields)
     else:
         _meta.fields = fields
     return super(QueryObjectType, cls).__init_subclass_with_meta__(
         _meta=_meta, **options
     )
예제 #6
0
 def __init_subclass_with_meta__(cls,
                                 declarative_base,
                                 exclude_models=None,
                                 _meta=None,
                                 **options):
     """
     :param declarative_base: sqlalchemy's base
     :param exclude_models: exclude models
     :param _meta:
     :param options:
     :return:
     """
     if exclude_models is None:
         exclude_models = []
     if not _meta:
         _meta = ObjectTypeOptions(cls)
     fields = OrderedDict()
     fields["node"] = graphene.relay.Node.Field()
     models = [
         cls for cls in declarative_base._decl_class_registry.values()
         if isinstance(cls, type) and issubclass(cls, declarative_base)
     ]  # all models
     for model_obj in models:
         if model_obj.__name__ in exclude_models:
             continue
         fields.update({
             decapitalize(model_obj.__name__):
             graphene.relay.Node.Field(
                 SQLAlchemyObjectTypes().get(model_obj)),
             "%s_list" % decapitalize(model_obj.__name__):
             model_connection(model_obj),
         })
     if _meta.fields:
         _meta.fields.update(fields)
     else:
         _meta.fields = fields
     return super(QueryObjectType,
                  cls).__init_subclass_with_meta__(_meta=_meta, **options)
예제 #7
0
    def __init_subclass_with_meta__(cls,
                                    interfaces=(),
                                    possible_types=(),
                                    default_resolver=None,
                                    _meta=None,
                                    model=None,
                                    only_fields=(),
                                    exclude_fields=(),
                                    group_fields=(),
                                    **options):

        if not _meta:
            _meta = ObjectTypeOptions(cls)

        registry = get_global_registry()

        # TODO(Jozef): add group_fields option so each respective vote type is not
        # separate field but all will be returned in list with labels in another
        # list
        # if group_fields:
        #     grouped = {}
        #     for group in group_fields:
        #         grouped[group] = {}
        #         to_generate = []
        #         for field in model._meta.get_fields():

        django_fields = yank_fields_from_attrs(construct_fields(
            model,
            registry,
            only_fields,
            exclude_fields,
            convert_choices_to_enum=True),
                                               _as=Field)

        assert not (possible_types and cls.is_type_of), (
            "{name}.Meta.possible_types will cause type collision with {name}.is_type_of. "
            "Please use one or other.").format(name=cls.__name__)

        _meta.fields = django_fields

        _meta.interfaces = interfaces
        _meta.possible_types = possible_types
        _meta.default_resolver = default_resolver
        super().__init_subclass_with_meta__(_meta=_meta, **options)
예제 #8
0
 def json_schema_to_graphene_object_type(self, name, schema):
     """:return : type, object"""
     if schema['type'] in SchemaBuilder.SCALARS:
         return 'scalar', SchemaBuilder.TYPE_TRANSLATION[schema['type']]
     elif schema['type'] == 'array':
         if 'items' in schema:
             _, T = self.json_schema_to_graphene_object_type(
                 name, schema['items'])
             return 'array', T
         else:
             return 'array', graphene.String
     elif schema['type'] == 'object':
         if name in self.object_types:
             return 'object', self.object_types[name]
         options = ObjectTypeOptions(BaseOptions)
         options.fields = {'raw': graphene.Field(graphene.JSONString)}
         for field in schema['properties']:
             t, T = self.json_schema_to_graphene_object_type(
                 field, schema['properties'][field])
             if t == 'array':
                 resolver = lambda self, info, field=field, T=T: [
                     T(raw=sub_raw) for sub_raw in self.raw[field]
                 ]
                 options.fields[field] = graphene.Field(graphene.List(T),
                                                        resolver=resolver)
             elif t == 'object':
                 resolver = lambda self, info, field=field, T=T: T(
                     raw=self.raw[field])
                 options.fields[field] = graphene.Field(T,
                                                        resolver=resolver)
             else:
                 resolver = lambda self, info, field=field: self.raw[field]
                 options.fields[field] = graphene.Field(T,
                                                        resolver=resolver)
         object_type = graphene.ObjectType.create_type(class_name=name,
                                                       _meta=options)
         self.object_types[name] = object_type
         return 'object', object_type
     else:
         print("UNKNOWN TYPE", schema['type'])
예제 #9
0
    def __init_subclass_with_meta__(
        cls,
        interfaces: Tuple[Type[SQLAlchemyInterface]] = (),
        models: Tuple[Type[DeclarativeMeta]] = (),
        excluded_models: Tuple[Type[DeclarativeMeta]] = (),
        exclude_model_fields: Tuple[str] = (),
        node_interface: Type[Node] = Node,
        default_resolver: ResolveInfo = None,
        _meta=None,
        **options,
    ):
        if not _meta:
            _meta = ObjectTypeOptions(cls)

        fields = OrderedDict()

        for interface in interfaces:
            if issubclass(interface, SQLAlchemyInterface):
                # sets fields and attrs based on model columns not all sqla properties
                SQLAlchemyAutoSchemaFactory.set_fields_and_attrs(
                    cls, interface, fields)
        for model in excluded_models:
            if model in models:
                models = (models[:models.index(model)] +
                          models[models.index(model) + 1:])
        possible_types = ()
        for model in models:
            model_name = model.__name__
            _model_name = to_snake_case(model.__name__)
            if hasattr(cls, _model_name):
                continue
            if hasattr(cls, "all_{}".format(pluralize_name(_model_name))):
                continue

            _model_interfaces = []

            for iface in interfaces:
                if issubclass(model, iface._meta.model):
                    _model_interfaces.append(iface)

            if not _model_interfaces:
                _model_interfaces = [node_interface]

            _node_class = type(
                model_name,
                (SQLAlchemyObjectType, ),
                {
                    "Meta": {
                        "model": model,
                        "interfaces": (tuple(_model_interfaces)),
                        "only_fields": [],
                        "exclude_fields": exclude_model_fields
                    }
                },
            )
            fields["all_{}".format(pluralize_name(
                _model_name))] = SQLAlchemyFilteredConnectionField(_node_class)
            setattr(
                cls,
                "all_{}".format(pluralize_name(_model_name)),
                SQLAlchemyFilteredConnectionField(_node_class),
            )
            iface = _model_interfaces[0]
            fields[_model_name] = iface.Field(_node_class)
            setattr(cls, _model_name, iface.Field(_node_class))
            possible_types += (_node_class, )
        if _meta.fields:
            _meta.fields.update(fields)
        else:
            _meta.fields = fields
        _meta.schema_types = possible_types

        super(SQLAlchemyAutoSchemaFactory, cls).__init_subclass_with_meta__(
            _meta=_meta, default_resolver=default_resolver, **options)