Пример #1
0
 def assert_field_converted(self, nautilus_field, graphene_field):
     # convert the nautilus field to the corresponding graphene type
     test_graphene_type = convert_peewee_field(nautilus_field)
     # make sure the converted type matches the graphene field
     assert isinstance(test_graphene_type, graphene_field), (
         "nautilus field was not properly coverted to %s" %
         graphene_field.__class__)
Пример #2
0
    def __new__(cls, name, bases, attributes, **kwds):

        full_attr = {}

        try:
            # for each field in the table
            for field in attributes['Meta'].model.fields():
                # the name of the field in the schema
                field_name = field.name[0].lower() + field.name[1:]
                # add an entry for the field we were passed
                full_attr[field_name] = convert_peewee_field(field)
        # if there is no meta type defined
        except KeyError:
            # keep going
            pass
        # if there is no model defined
        except AttributeError:
            # yell loudly
            raise ValueError("PeeweeObjectsTypes must have a model.")


        # merge the given attributes ontop of the dynamic ones
        full_attr.update(attributes)

        # create the nex class records
        return super().__new__(cls, name, bases, full_attr, **kwds)
Пример #3
0
def args_for_model(model):
    # import the model field helper
    from .util import fields_for_model

    # figure use each field as a filter
    args = fields_for_model(model)
    # add the pk argument
    args['pk'] = convert_peewee_field(model.primary_key())
    # create a copy of the argument dict we can mutate
    full_args = args.copy()

    # todo: add type-specific filters
    # go over the arguments
    for arg, field_type in args.items():
        # add the list member filter
        full_args[arg + '_in'] = List(field_type)

    # add integer valued model filters
    for arg in ['first', 'last', 'offset']:
        # add the arg to the dict
        full_args[arg] = Int()

    # add the list of string values model filters
    for arg in ['order_by']:
        # add the arg to the dict
        full_args[arg] = List(GraphQLString)

    # return the complete dictionary of arguments
    return full_args
Пример #4
0
 def assert_field_converted(self, nautilus_field, graphene_field):
     # convert the nautilus field to the corresponding graphene type
     test_graphene_type = convert_peewee_field(nautilus_field)
     # make sure the converted type matches the graphene field
     assert isinstance(test_graphene_type, graphene_field), (
         "nautilus field was not properly coverted to %s" % graphene_field.__class__
     )
Пример #5
0
def args_for_model(model):
    # import the model field helper
    from .util import fields_for_model

    # figure use each field as a filter
    args = fields_for_model(model)
    # add the pk argument
    args['pk'] = convert_peewee_field(model.primary_key())
    # create a copy of the argument dict we can mutate
    full_args = args.copy()

    # todo: add type-specific filters
    # go over the arguments
    for arg, field_type in args.items():
        # add the list member filter
        full_args[arg + '_in'] = List(field_type)

    # add integer valued model filters
    for arg in ['first', 'last', 'offset']:
        # add the arg to the dict
        full_args[arg] = Int()

    # add the list of string values model filters
    for arg in ['order_by']:
        # add the arg to the dict
        full_args[arg] = List(GraphQLString)

    # return the complete dictionary of arguments
    return full_args
Пример #6
0
def _summarize_object_type(model):
    """
        This function returns the summary for a given model
    """
    # the fields for the service's model
    model_fields = {field.name: field for field in list(model.fields())}
    # summarize the model
    return {
        'fields': [{
            'name': key,
            'type': type(convert_peewee_field(value)).__name__
        } for key, value in model_fields.items()]
    }
Пример #7
0
def _summarize_object_type(model):
    """
        This function returns the summary for a given model
    """
    # the fields for the service's model
    model_fields = {field.name: field for field in list(model.fields())}
    # summarize the model
    return {
        'fields': [{
            'name': key,
            'type': type(convert_peewee_field(value)).__name__
            } for key, value in model_fields.items()
        ]
    }
Пример #8
0
def fields_for_model(model):
    """
        This function returns the fields for a schema that matches the provided
        nautilus model.

        Args:
            model (nautilus.model.BaseModel): The model to base the field list on

        Returns:
            (dict<field_name: str, graphqlType>): A mapping of field names to
                graphql types
    """

    # the attribute arguments (no filters)
    args = {field.name.lower() : convert_peewee_field(field) \
                                        for field in model.fields()}
    # use the field arguments, without the segments
    return args
Пример #9
0
def fields_for_model(model):
    """
        This function returns the fields for a schema that matches the provided
        nautilus model.

        Args:
            model (nautilus.model.BaseModel): The model to base the field list on

        Returns:
            (dict<field_name: str, graphqlType>): A mapping of field names to
                graphql types
    """

    # the attribute arguments (no filters)
    args = {field.name.lower() : convert_peewee_field(field) \
                                        for field in model.fields()}
    # use the field arguments, without the segments
    return args
Пример #10
0
    def summarize(self, **extra_fields):
        # the fields for the service's model
        model_fields = {field.name: field for field in list(self.model.fields())} \
                            if self.model \
                            else {}

        # add the model fields to the dictionary
        return dict(
            **super().summarize(),
            fields=[{
                    'name': key,
                    'type': type(convert_peewee_field(value)).__name__
                    } for key, value in model_fields.items()
                   ],
            mutations=[
                summarize_crud_mutation(model=self, method='create'),
                summarize_crud_mutation(model=self, method='update'),
                summarize_crud_mutation(model=self, method='delete'),
            ],
            **extra_fields
        )
Пример #11
0
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
Пример #12
0
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
Пример #13
0
def _graphql_type_string(value):
    return type(convert_peewee_field(value)).__name__
Пример #14
0
def _graphql_type_string(value):
    return type(convert_peewee_field(value)).__name__
Пример #15
0
def serialize_native_type(native_type):
    """
        This function serializes the native object type for summaries
    """
    return type(convert_peewee_field(native_type)).__name__