Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Optimize fetching categories by using cache
Marcin Gębala682f6d999faf
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.pyindex 5900613b6b..00173fab0b 100644--- a/saleor/graphql/api.py+++ b/saleor/graphql/api.py@@ -11,7 +11,20 @@ from ..product.models import (AttributeChoiceValue, Category, Product,ProductAttribute, ProductImage, ProductVariant)from ..product.utils import get_availabilityfrom .scalars import AttributesFilterScalar-from .utils import DjangoPkInterface, connection_with_count, get_object_or_none+from .utils import (CategoryAncestorsCache, DjangoPkInterface,+ connection_with_count)+++CONTEXT_CACHE_NAME = '__cache__'+CACHE_ANCESTORS = 'ancestors'+++def get_ancestors_from_cache(category, context):+ cache = getattr(context, CONTEXT_CACHE_NAME, None)+ if cache and CACHE_ANCESTORS in cache:+ return cache[CACHE_ANCESTORS].get(category)+ else:+ return category.get_ancestors()class ProductAvailabilityType(graphene.ObjectType):@@ -83,7 +96,7 @@ class CategoryType(DjangoObjectType):interfaces = (relay.Node, DjangoPkInterface)def resolve_ancestors(self, args, context, info):- return self.get_ancestors()+ return get_ancestors_from_cache(self, context)def resolve_children(self, args, context, info):return self.children.all()@@ -91,8 +104,14 @@ class CategoryType(DjangoObjectType):def resolve_siblings(self, args, context, info):return self.get_siblings()- def resolve_products(self, args, context, info):+ def resolve_products_count(self, args, context, info):+ return self.products.count()++ def resolve_url(self, args, context, info):+ ancestors = get_ancestors_from_cache(self, context)+ return self.get_absolute_url(ancestors)+ def resolve_products(self, args, context, info):def filter_by_price(queryset, value, operator):return [obj for obj in queryset if operator(get_availability(obj, context.discounts).price_range.min_price.gross, value)]@@ -149,12 +168,6 @@ class CategoryType(DjangoObjectType):qs = filter_by_price(qs, price_gte, operator.ge)return qs- def resolve_products_count(self, args, context, info):- return self.products.count()-- def resolve_url(self, args, context, info):- return self.get_absolute_url()-class ProductVariantType(DjangoObjectType):stock_quantity = graphene.Int()@@ -220,9 +233,13 @@ class Viewer(graphene.ObjectType):debug = graphene.Field(DjangoDebug, name='__debug')def resolve_category(self, args, context, info):- category = get_object_or_none(- Category.objects.prefetch_related('children'), pk=args.get('pk'))- return category+ categories = Category.tree.filter(pk=args.get('pk')).get_cached_trees()+ if categories:+ category = categories[0]+ cache = {CACHE_ANCESTORS: CategoryAncestorsCache(category)}+ setattr(context, CONTEXT_CACHE_NAME, cache)+ return category+ return Nonedef resolve_attributes(self, args, context, info):category_pk = args.get('category_pk')diff --git a/saleor/graphql/utils.py b/saleor/graphql/utils.pyindex 88f18e72a8..f8190695fc 100644--- a/saleor/graphql/utils.py+++ b/saleor/graphql/utils.py@@ -3,18 +3,20 @@ import graphenefrom django.shortcuts import _get_queryset-def get_object_or_none(klass, *args, **kwargs):- queryset = _get_queryset(klass)- try:- return queryset.get(*args, **kwargs)- except AttributeError:- klass__name = klass.__name__ if isinstance(klass, type) else klass.__class__.__name__- raise ValueError(- "First argument to get_object_or_none() must be a Model, Manager, "- "or QuerySet, not '%s'." % klass__name- )- except queryset.model.DoesNotExist:- return None+class CategoryAncestorsCache(object):+ """+ Cache used to store ancestors of a category in GraphQL context in order to+ reduce number of database queries. Categories of the same tree depth level+ have common ancestors, which allows us to cache them by the level.+ """++ def __init__(self, category):+ self._cache = {category.level: category.get_ancestors()}++ def get(self, category):+ if category.level not in self._cache:+ self._cache[category.level] = category.get_ancestors()+ return self._cache[category.level]class DjangoPkInterface(graphene.Interface):@@ -39,3 +41,17 @@ def connection_with_count(_type):return len(self.edges)return Connection+++def get_object_or_none(klass, *args, **kwargs):+ queryset = _get_queryset(klass)+ try:+ return queryset.get(*args, **kwargs)+ except AttributeError:+ klass__name = klass.__name__ if isinstance(klass, type) else klass.__class__.__name__+ raise ValueError(+ "First argument to get_object_or_none() must be a Model, Manager, "+ "or QuerySet, not '%s'." % klass__name+ )+ except queryset.model.DoesNotExist:+ return Nonediff --git a/saleor/product/models/base.py b/saleor/product/models/base.pyindex beeaad0219..ce17271c22 100644--- a/saleor/product/models/base.py+++ b/saleor/product/models/base.py@@ -52,16 +52,18 @@ class Category(MPTTModel):def __str__(self):return self.name- def get_absolute_url(self):+ def get_absolute_url(self, ancestors=None):return reverse('product:category',- kwargs={'path': self.get_full_path(),+ kwargs={'path': self.get_full_path(ancestors),'category_id': self.id})- def get_full_path(self):+ def get_full_path(self, ancestors=None):if not self.parent_id:return self.slug- return '/'.join(- [node.slug for node in self.get_ancestors(include_self=True)])+ if not ancestors:+ ancestors = self.get_ancestors()+ nodes = [node for node in ancestors] + [self]+ return '/'.join([node.slug for node in nodes])class Meta:verbose_name_plural = 'categories'