Exemplo n.º 1
0
class Query(object):
    all_data_sources = ConnectionField(DataSourceConnection)
    data_source = ConnectionField(DataSourceDataConnection, name=String(required=True))

    def resolve_all_data_sources(self, info):
        return get_data_sources()

    def resolve_data_source(self, info, name):
        return get_data_source_data(info, name)
Exemplo n.º 2
0
class Query(ObjectType):
    all_data_sources = ConnectionField(DataSourceConnection)
    data_source = ConnectionField(DataSourceDataConnection, name=String(required=True))

    def resolve_all_data_sources(self, info, **kwargs):
        return get_data_sources()

    def resolve_data_source(self, info, name, **kwargs):
        return get_data_source_data(info.context.user, name)
Exemplo n.º 3
0
class UserNode(DjangoObjectType):
    class Meta:
        model = get_user_model()
        filter_fields = {
            'username': ['exact', 'icontains', 'istartswith'],
        }
        interfaces = (relay.Node, )
        connection_class = FollowerConnection
        connection_class = FollowingConnection

    # Additional Fields
    recipes = ConnectionField(RecipeConnection)
    # We are establishing the field in our node
    # As the custom connection class we made above
    collections = ConnectionField(CollectionConnection)
    total_recipes = Int(
        description="Returns the total amount of recipes the user has")
    total_followers = Int(
        description=
        "Returns the total amount of users that are following the user")
    total_following = Int(
        description="Returns the total amount of users being followed")

    @staticmethod
    def resolve_followers(self, context, **kwargs):
        return self.followers.all()

    @staticmethod
    def resolve_total_followers(self, context, **kwargs):
        return self.amount_of_followers

    @staticmethod
    def resolve_following(self, context, **kwargs):
        return self.following.all()

    @staticmethod
    def resolve_total_following(self, context, **kwargs):
        return self.amount_of_users_following

    @staticmethod
    def resolve_recipes(self, context, **kwargs):
        return self.recipes.all()

    @staticmethod
    def resolve_collections(self, context, **kwargs):
        return self.collections.all()

    @staticmethod
    def resolve_total_recipes(self, context, **kwargs):
        return len(self.recipes.all())
Exemplo n.º 4
0
class AnalyticsTable(DjangoObjectType):
    available_fields = ConnectionField(
        AvailableFieldConnection,
        prefix=String(required=False),
        depth=graphene.Int(required=False),
    )
    result_data = graphene.Field(AnalyticsOutput)

    @staticmethod
    def resolve_available_fields(obj, info, prefix=None, depth=None, **kwargs):
        start = obj.get_starting_object(info)

        depth = depth if depth and depth > 0 else 1
        prefix = prefix.split(".") if prefix else []

        return [
            {
                "id": ".".join(field.source_path()),
                "label": field.label,
                "full_label": field.full_label(),
                "source_path": ".".join(field.source_path()),
                "is_leaf": field.is_leaf(),
                "is_value": field.is_value(),
            }
            for path, field in start.get_fields(prefix, depth).items()
        ]

    @staticmethod
    def resolve_result_data(obj, info):
        return simple_table.SimpleTable(obj)

    class Meta:
        model = models.AnalyticsTable
        interfaces = (relay.Node,)
        connection_class = CountableConnectionBase
Exemplo n.º 5
0
class RecipeNode(DjangoObjectType):
    class Meta:
        model = Recipe
        filter_fields = {
            'name': ['exact', 'icontains', 'istartswith'],
            'tags': ['icontains', 'istartswith'],
        }
        interfaces = (relay.Node, )

    steps = ConnectionField(StepConnection)
    likes = Int(description="The amount of likes for each Recipe")
    comments = Int(description="The total amount of comments")
    difficulty_level = String(
        description="Returns the difficulty level in a human-readable Form")
    # This creates a field in the RecipeNode that we can call
    # Using the staticmethod

    @staticmethod
    def resolve_steps(self, context, **kwargs):
        return self.steps.all()

    @staticmethod
    def resolve_likes(self, context, **kwargs):
        return self.amount_of_likes

    @staticmethod
    def resolve_comments(self, context, **kwargs):
        return self.total_comments

    @staticmethod
    def resolve_difficulty_level(self, context, **kwargs):
        return self.difficulty_level
Exemplo n.º 6
0
class Query(graphene.ObjectType):
    """Gasoline Query class"""
    all_stations = ConnectionField(StationConnection)
    all_prices = ConnectionField(PriceConnection)

    def resolve_all_stations(root, info, **kwargs):
        """ Return all the stations """
        return Station.objects.filter(is_active=True)

    def resolve_all_prices(root, info, **kwargs):
        """ Return all prices """
        return Price.objects.filter(station__is_active=True)

    # Node Query class
    station = relay.Node.Field(StationNode)
    node_station = DjangoFilterConnectionField(StationNode)

    price = relay.Node.Field(PriceNode)
    node_price = DjangoFilterConnectionField(PriceNode)
Exemplo n.º 7
0
class AnalyticsTable(DjangoObjectType):
    available_fields = ConnectionField(
        AvailableFieldConnection,
        prefix=String(required=False),
        depth=graphene.Int(required=False),
    )
    result_data = graphene.Field(AnalyticsOutput)
    starting_object = StartingObject(required=False)

    @staticmethod
    def resolve_available_fields(obj, info, prefix=None, depth=None, **kwargs):
        start = obj.get_starting_object(info)

        depth = depth if depth and depth > 0 else 1
        prefix = prefix.split(".") if prefix else []

        return sorted(
            [{
                "id": ".".join(field.source_path()),
                "label": field.label,
                "full_label": field.full_label(),
                "source_path": ".".join(field.source_path()),
                "is_leaf": field.is_leaf(),
                "is_value": field.is_value(),
                "supported_functions": field.supported_functions(),
            } for path, field in start.get_fields(prefix, depth).items()],
            key=lambda field: field["id"],
        )

    @staticmethod
    def resolve_result_data(obj, info):
        return (simple_table.SimpleTable(obj)
                if obj.is_extraction() else pivot_table.PivotTable(obj))

    class Meta:
        model = models.AnalyticsTable
        interfaces = (relay.Node, )
        connection_class = CountableConnectionBase
        fields = [
            "slug",
            "meta",
            "created_by_group",
            "created_by_user",
            "modified_by_group",
            "modified_by_user",
            "created_at",
            "modified_at",
            "disable_visibilities",
            "available_fields",
            "result_data",
            "fields",
            "name",
            "starting_object",
        ]
Exemplo n.º 8
0
class Query(graphene.ObjectType):
    stores = ConnectionField(StoreLocation_Connection, store_type=graphene.Int())
    store_detail = graphene.Field(StoreLocationObjectType, id=graphene.Int(required=True))
    store_admin = graphene.Field(StoreType)
    favorite_stores = ConnectionField(StoreLocation_Connection)
    booking_stores = graphene.List(BookingType, store_id=graphene.Int(required=True))
    mine_stores = graphene.List('apps.users.schema.StoreManagerProfileType')
    get_store_by_filter = graphene.List(StoreType, store_type=graphene.Int())
    get_all_staff_members = graphene.List('apps.users.schema.StoreManagerProfileType', store_id=graphene.Int(), searchBy=graphene.String(), role=graphene.Int())
    def resolve_stores(self, info, **kwargs):
        return getTrucksBusinessLogically.byBusinessType(kwargs['store_type'])

    def resolve_mine_stores(self, info):
        return info.context.user.stores_manager_profile.all().order_by('-id')

    def resolve_store_detail(self, info, id):
        return get_object_or_404(StoreLocations, id=id)

    def resolve_store_admin(self, info):
        return get_object_or_404(Store, id=info.context.store_profile.store.id)
    
    def resolve_favorite_stores(self, info, **kwargs):
        return Preferences.objects.get(account=info.context.user).fav_stores.all()

    def resolve_booking_stores(self, info, store_id):
        return info.context.user.reservations.filter(store=store_id).exclude(status=3)

    def resolve_get_store_by_filter(self, info, **kwargs):
        return Store.objects.filter(**kwargs)

    def resolve_get_all_staff_members(self, info, store_id, **kwargs):
        staffs = StoreManagerProfile.objects.filter(store_id=store_id)
        if 'searchBy' in kwargs:
            user = User.objects.filter(Q(first_name__icontains=kwargs['searchBy']) | Q(email__icontains=kwargs['searchBy'])).values('id')
            staffs = staffs.filter(user_id__in=user)
        
        if 'role' in kwargs:
            staffs = staffs.filter(role=kwargs['role'])
        return staffs.order_by('role')
Exemplo n.º 9
0
class AnalyticsOutput(ObjectType):
    records = ConnectionField(AnalyticsTableContent)

    @staticmethod
    def resolve_records(table, info, *args, **kwargs):
        rows = [
            AnalyticsRow(edges=[{
                "node": {
                    "alias": alias,
                    "value": val
                }
            } for alias, val in row.items()]) for row in table.get_records()
        ]
        return rows
Exemplo n.º 10
0
class CollectionNode(DjangoObjectType):
    class Meta:
        model = Collection
        filter_fields = {
            'name': ['exact', 'icontains', 'istartswith'],
            'info': ['icontains', 'istartswith'],
        }
        interfaces = (relay.Node, )

    recipes = ConnectionField(CollectionRecipeConnection)

    @staticmethod
    def resolve_recipes(self, context, **kwargs):
        return self.recipes.all()
Exemplo n.º 11
0
class ItemInterface(graphene.Interface):
    id = relay.GlobalID()
    parent_id = relay.GlobalID()
    foo = graphene.String()
    title = graphene.String()
    unoptimized_title = graphene.String()
    item_type = graphene.String()
    father = graphene.Field('tests.schema.ItemType')
    all_children = graphene.List('tests.schema.ItemType')
    children_names = graphene.String()
    aux_children_names = graphene.String()
    filtered_children = graphene.List(
        'tests.schema.ItemType',
        name=graphene.String(required=True),
    )
    children_custom_filtered = gql_optimizer.field(
        ConnectionField('tests.schema.ItemConnection',
                        filter_input=ItemFilterInput()),
        prefetch_related=_prefetch_children,
    )

    def resolve_foo(root, info):
        return 'bar'

    @gql_optimizer.resolver_hints(
        model_field=lambda: 'children', )
    def resolve_children_names(root, info):
        return ' '.join(item.name for item in root.children.all())

    @gql_optimizer.resolver_hints(
        prefetch_related='children', )
    def resolve_aux_children_names(root, info):
        return ' '.join(item.name for item in root.children.all())

    @gql_optimizer.resolver_hints(
        prefetch_related=lambda info, name: Prefetch(
            'children',
            queryset=gql_optimizer.query(Item.objects.filter(name=name), info),
            to_attr='gql_filtered_children_' + name,
        ),
    )
    def resolve_filtered_children(root, info, name):
        return getattr(root, 'gql_filtered_children_' + name)

    def resolve_children_custom_filtered(root, info, *_args):
        return getattr(root, 'gql_custom_filtered_children')
Exemplo n.º 12
0
class StepNode(DjangoObjectType):
    class Meta:
        model = Step
        filter_fields = {
            'name': ['exact', 'icontains', 'istartswith'],
            'explanation': ['exact', 'icontains', 'istartswith'],
        }
        interfaces = (relay.Node, )

    comments = ConnectionField(CommentConnection)
    total_likes = Int(description="The amount of likes per each step")

    @staticmethod
    def resolve_comments(self, context, **kwargs):
        return self.comments.all()

    @staticmethod
    def resolve_total_likes(self, context, **kwargs):
        # This will return a total amount of likes per step
        return self.amount_of_likes
Exemplo n.º 13
0
class Query(graphene.ObjectType):
    rates_by_store = ConnectionField(RateTypeConnection, store_id=graphene.Int(required=True))
    start_list = graphene.Field(ListPointType, store_id=graphene.Int())

    def resolve_rates_by_store(self, info, store_id, **kwargs):
        return Rate.objects.filter(store=store_id).annotate(sort_order_auth=Case(When(rater=info.context.user, then=('id')))).order_by('sort_order_auth')

    def resolve_start_list(self, info, store_id):
        rate_all = Rate.objects.filter(store=store_id).count()
        if rate_all == 0:
            rate_all = 1
        start_object = {
            'start_1': (Rate.objects.filter(store=store_id, point=1).count()/rate_all) * 100,
            'start_2': (Rate.objects.filter(store=store_id, point=2).count()/rate_all) * 100,
            'start_3': (Rate.objects.filter(store=store_id, point=3).count()/rate_all) * 100,
            'start_4': (Rate.objects.filter(store=store_id, point=4).count()/rate_all) * 100,
            'start_5': (Rate.objects.filter(store=store_id, point=5).count()/rate_all) * 100,
            'total': rate_all
            
        }
        return start_object
Exemplo n.º 14
0
def node_connection_field(model_class, query_class, node_class, description):
    """ Make a ConnectionField for a model class

    :param query_class: query class for model
    :param node_class: ObjectType
    :param description: string describing the collection
    :return: ConnectionField
    """
    entity_name = node_class.__name__

    class NodeConnection(object):
        @with_session
        def resolve_total_count(self, args, context, info, session):
            return len(query_class(session))

        @with_session
        def resolve_filtered_count(self, args, context, info, session):
            return context['count']

        @with_session
        def resolve_page_info(self, args, context, info, session):
            return context['pageInfo']

    connection_class = type(
        '{}Connection'.format(entity_name),
        # inherit class methods from NodeConnection and other behaviour from
        # graphene.relay.Connection
        (NodeConnection, Connection),
        # equivalent to
        # total_count = graphene.Int()
        # filtered_count = graphene.Int()
        # class Meta:
        #     node = node_class
        {
            'total_count': graphene.Int(),
            'filtered_count': graphene.Int(),
            'Meta': type('Meta', (object, ), {
                'node': node_class,
            })
        })

    untyped_filter_field_group = model_class.properties.derive(
        field_group_class=PartialDictFieldGroup)
    typed_filter_field_group = model_class.internal.derive(
        field_group_class=PartialDictFieldGroup)
    filter_casts = _filter_casts(model_class, typed_filter_field_group)
    filter_to_internal = Mapping(untyped_filter_field_group,
                                 typed_filter_field_group,
                                 field_casts=filter_casts)

    camel_case_field_group = model_class.properties.derive(
        snake_to_camel_case, PartialDictFieldGroup)
    order_by_field_group = model_class.internal.derive(make_boolean,
                                                       PartialDictFieldGroup)
    order_by_to_mapped = Mapping(camel_case_field_group, order_by_field_group)

    @with_session
    def resolver(self, args, context, info, session):
        query = query_class(session)

        filters = args.get('filters')
        if filters:
            typed = filter_to_internal.cast_from(filters)
            criteria = tuple(query.criteria_from_dict(typed))
            query.filter(*criteria)

        filtered_count = len(query)

        order_by = args.get('orderBy')
        if order_by:
            order_by_values = OrderedDict(_parse_order_by(order_by))
            mapped = order_by_to_mapped.cast_from(order_by_values)
            # TODO only add this sort by id if there is no other sort by a unique field
            # required in order have stable sorting and paging when sorting by a non-unique field
            mapped['_id'] = True
            criteria = tuple(query.sort_criteria_from_dict(mapped))
            query.order_by(*criteria)

        offset = 0
        after = args.get('after')
        if after:
            offset = int(Node.from_global_id(after)[1])
            query.offset(offset)
            offset += 1
            args.pop('after')

        first = args.get('first')
        if first:
            limit = int(first)
            query.limit(limit)

        instances = list(query.collection())

        context['count'] = filtered_count
        context['pageInfo'] = PageInfo(
            start_cursor=offset_to_cursor(query.start_index),
            end_cursor=offset_to_cursor(query.end_index),
            has_previous_page=False
            if query.start_index is None else query.start_index > 0,
            has_next_page=False if query.end_index is None else
            query.end_index < filtered_count - 1)
        return instances

    # equivalent to
    # class SomeFilterInput(graphene.InputObjectType):
    #   refNo = graphene.Argument(graphene.Int)
    #   ...
    filter_input = type('{}FilterInput'.format(entity_name),
                        (graphene.InputObjectType, ),
                        get_filter_fields(model_class))

    connection_field = ConnectionField(
        connection_class,
        resolver=resolver,
        description=description,
        filters=graphene.Argument(filter_input),
        orderBy=graphene.Argument(graphene.String),
    )

    return connection_field
class ItemInterface(graphene.Interface):
    id = graphene.ID(required=True)
    parent_id = graphene.ID()
    foo = graphene.String()
    title = graphene.String()
    unoptimized_title = graphene.String()
    item_type = graphene.String()
    father = graphene.Field('tests.schema.ItemType')
    all_children = graphene.List('tests.schema.ItemType')
    prefetched_children = graphene.List('tests.schema.ItemType')
    children_names = graphene.String()
    aux_children_names = graphene.String()
    filtered_children = graphene.List(
        'tests.schema.ItemType',
        name=graphene.String(required=True),
    )
    children_custom_filtered = gql_optimizer.field(
        ConnectionField('tests.schema.ItemConnection',
                        filter_input=ItemFilterInput()),
        prefetch_related=_prefetch_children,
    )
    children_count = graphene.Int()
    name_with_prefix = graphene.String(prefix=graphene.String(required=True))

    def resolve_foo(root, info):
        return 'bar'

    @gql_optimizer.resolver_hints(
        model_field='children', )
    def resolve_children_names(root, info):
        return ' '.join(item.name for item in root.children.all())

    @gql_optimizer.resolver_hints(prefetch_related=lambda info: Prefetch(
        "children",
        queryset=gql_optimizer.QueryOptimizer(
            info, parent_id_field="parent_id").optimize(Item.objects.all()),
        to_attr="gql_prefetched_children",
    ))
    def resolve_prefetched_children(root, info):
        return getattr(root, 'gql_prefetched_children')

    @gql_optimizer.resolver_hints(
        prefetch_related='children', )
    def resolve_aux_children_names(root, info):
        return ' '.join(item.name for item in root.children.all())

    @gql_optimizer.resolver_hints(
        prefetch_related=lambda info, name: Prefetch(
            'children',
            queryset=gql_optimizer.query(Item.objects.filter(name=name), info),
            to_attr='gql_filtered_children_' + name,
        ),
    )
    def resolve_filtered_children(root, info, name):
        return getattr(root, 'gql_filtered_children_' + name)

    def resolve_children_custom_filtered(root, info, *_args):
        return getattr(root, 'gql_custom_filtered_children')

    @gql_optimizer.resolver_hints(
        annotate={'gql_children_count': Count('children')})
    def resolve_children_count(root, info):
        return getattr(root, 'gql_children_count')

    @gql_optimizer.resolver_hints(
        annotate=lambda info, prefix: {
            'gql_name_with_prefix':
            Concat(
                Value(prefix), Value(' '), F('name'), output_field=CharField())
        })
    def resolve_name_with_prefix(root, info, prefix):
        return getattr(root, 'gql_name_with_prefix')
class CommonQuery(object):

    user = graphene.Field(UserQL,
                          id=graphene.Int(),
                          username=graphene.String())

    risktype = graphene.Field(RiskTypeQL,
                              id=graphene.Int(),
                              risk_type_name=graphene.String(),
                              risk_type_description=graphene.String())

    risktypefield = graphene.Field(RiskTypeFieldQL)

    risk = graphene.Field(RiskQL,
                          id=graphene.Int(),
                          risk_name=graphene.String(),
                          risk_description=graphene.String(),
                          risktype=graphene.Int())

    all_users = graphene.List(UserQL)

    all_risks = graphene.List(RiskQL, risktype=graphene.Int())

    risks = ConnectionField(Risk_Connection,
                            risktype=graphene.Int(),
                            risk_name=graphene.String())

    def resolve_risks(self, info, **kwargs):
        # return Risk.objects.all()
        nRiskType = 1
        strRiskName = ''
        for arg in kwargs:
            if (arg is 'risktype' and arg is not None):
                nRiskType = kwargs[arg]
                risks = Risk.objects.select_related("risktype").all()
                return risks.filter(risktype=nRiskType).order_by('risk_name')
            elif (arg is 'risk_name' and arg is not None):
                strRiskName = kwargs[arg]
                # Model.objects.filter(adv_images__regex=r'^\d+')[:3]
                strRiskName = "^" + strRiskName + ".*?$"
                return Risk.objects.filter(
                    risk_name__regex=strRiskName).order_by('risk_name')

        # if risktype is None return all objects
        return Risk.objects.select_related("risktype").all().order_by(
            'risk_name')

    def resolve_all_users(self, context):
        # We can easily optimize query count in the resolve method
        return User.objects.all()

    def resolve_user(self, context, id=None, username=None):
        if id is not None:
            return User.objects.get(pk=id)

        if username is not None:
            return User.objects.get(username=username)

        return None

    def resolve_all_risks(self, context, risktype=None):
        # Filter based on risktype if available
        if risktype is not None:
            allrisks = Risk.objects.select_related("risktype").all()
            return allrisks.filter(risktype=risktype)

        # We can easily optimize query count in the resolve method
        return Risk.objects.select_related("risktype").all()

    def resolve_risk(self, context, id=None, risk_name=None, risktype=None):
        if id is not None:
            return Risk.objects.get(pk=id)

        if risk_name is not None:
            return Risk.objects.get(risk_name=risk_name)

        if risktype is not None:
            return Risk.objects.get(risktype=risktype)

        return None
Exemplo n.º 17
0
class ItemInterface(graphene.Interface):
    id = relay.GlobalID()
    parent_id = relay.GlobalID()
    foo = graphene.String()
    title = graphene.String()
    unoptimized_title = graphene.String()
    item_type = graphene.String()
    father = graphene.Field("tests.schema.ItemType")
    all_children = graphene.List("tests.schema.ItemType")
    children_names = graphene.String()
    aux_children_names = graphene.String()
    filtered_children = graphene.List(
        "tests.schema.ItemType",
        name=graphene.String(required=True),
    )
    aux_filtered_children = graphene.List(
        "tests.schema.ItemType",
        name=graphene.String(required=True),
    )
    children_custom_filtered = gql_optimizer.field(
        ConnectionField("tests.schema.ItemConnection", filter_input=ItemFilterInput()),
        prefetch_related=_prefetch_children,
    )

    def resolve_foo(root, info):
        return "bar"

    @gql_optimizer.resolver_hints(
        model_field=lambda: "children",
    )
    def resolve_children_names(root, info):
        return " ".join(item.name for item in root.children.all())

    @gql_optimizer.resolver_hints(
        prefetch_related="children",
    )
    def resolve_aux_children_names(root, info):
        return " ".join(item.name for item in root.children.all())

    @gql_optimizer.resolver_hints(
        prefetch_related=lambda info, name: Prefetch(
            "children",
            queryset=gql_optimizer.query(Item.objects.filter(name=name), info),
            to_attr="gql_filtered_children_" + name,
        ),
    )
    def resolve_filtered_children(root, info, name):
        return getattr(root, "gql_filtered_children_" + name)

    @gql_optimizer.resolver_hints(
        prefetch_related=lambda info, name: Prefetch(
            "children",
            queryset=gql_optimizer.query(
                Item.objects.filter(name=f"some_prefix {name}"), info
            ),
            # Different queryset than resolve_filtered_children but same to_attr, on purpose
            # to check equality of Prefetch is based only on to_attr attribute, as it is implemented in Django.
            to_attr="gql_filtered_children_" + name,
        ),
    )
    def resolve_aux_filtered_children(root, info, name):
        return getattr(root, "gql_filtered_children_" + name)

    def resolve_children_custom_filtered(root, info, *_args):
        return getattr(root, "gql_custom_filtered_children")