Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Use replica to resolve default channel (#15542)
Marcin Gębala3a04b323c490
diff --git a/saleor/channel/utils.py b/saleor/channel/utils.pyindex ecce4b96a4..1f214290d3 100644--- a/saleor/channel/utils.py+++ b/saleor/channel/utils.py@@ -1,5 +1,7 @@import warnings+from django.conf import settings+from .exceptions import ChannelNotDefined, NoDefaultChannelfrom .models import Channel@@ -10,7 +12,7 @@ DEPRECATION_WARNING_MESSAGE = ()-def get_default_channel() -> Channel:+def get_default_channel(allow_replica: bool = False) -> Channel:"""Return a default channel.Returns a channel only when exactly one channel exists in the system. If there are@@ -23,10 +25,17 @@ def get_default_channel() -> Channel::raises NoDefaultChannel: When there are no channels."""+ if allow_replica:+ database_connection_name = settings.DATABASE_CONNECTION_REPLICA_NAME+ else:+ database_connection_name = settings.DATABASE_CONNECTION_DEFAULT_NAME+try:- channel = Channel.objects.get()+ channel = Channel.objects.using(database_connection_name).get()except Channel.MultipleObjectsReturned:- channels = list(Channel.objects.filter(is_active=True))+ channels = list(+ Channel.objects.using(database_connection_name).filter(is_active=True)+ )if len(channels) == 1:warnings.warn(DEPRECATION_WARNING_MESSAGE)return channels[0]diff --git a/saleor/graphql/account/mutations/account/account_register.py b/saleor/graphql/account/mutations/account/account_register.pyindex 28c480659f..5ccb0c361e 100644--- a/saleor/graphql/account/mutations/account/account_register.py+++ b/saleor/graphql/account/mutations/account/account_register.py@@ -130,7 +130,7 @@ class AccountRegister(ModelMutation):)data["channel"] = clean_channel(- data.get("channel"), error_class=AccountErrorCode+ data.get("channel"), error_class=AccountErrorCode, allow_replica=False).slugdata["email"] = data["email"].lower()diff --git a/saleor/graphql/account/mutations/account/account_request_deletion.py b/saleor/graphql/account/mutations/account/account_request_deletion.pyindex c8e068b508..c6f45b7af8 100644--- a/saleor/graphql/account/mutations/account/account_request_deletion.py+++ b/saleor/graphql/account/mutations/account/account_request_deletion.py@@ -64,7 +64,9 @@ class AccountRequestDeletion(BaseMutation):raise ValidationError({"redirect_url": error}, code=AccountErrorCode.INVALID.value)- channel_slug = clean_channel(channel, error_class=AccountErrorCode).slug+ channel_slug = clean_channel(+ channel, error_class=AccountErrorCode, allow_replica=False+ ).slugmanager = get_plugin_manager_promise(info.context).get()token = account_delete_token_generator.make_token(user) # type: ignorediff --git a/saleor/graphql/account/mutations/account/confirm_email_change.py b/saleor/graphql/account/mutations/account/confirm_email_change.pyindex f7a613efcd..25f284b7c1 100644--- a/saleor/graphql/account/mutations/account/confirm_email_change.py+++ b/saleor/graphql/account/mutations/account/confirm_email_change.py@@ -95,7 +95,9 @@ class ConfirmEmailChange(BaseMutation):user.email = new_emailuser.search_document = search.prepare_user_search_document_value(user)user.save(update_fields=["email", "search_document", "updated_at"])- channel_slug = clean_channel(channel, error_class=AccountErrorCode).slug+ channel_slug = clean_channel(+ channel, error_class=AccountErrorCode, allow_replica=False+ ).slugcls.post_save_action(info, user, channel_slug, old_email)diff --git a/saleor/graphql/account/mutations/account/request_email_change.py b/saleor/graphql/account/mutations/account/request_email_change.pyindex a905a597fa..22fd29c533 100644--- a/saleor/graphql/account/mutations/account/request_email_change.py+++ b/saleor/graphql/account/mutations/account/request_email_change.py@@ -98,7 +98,9 @@ class RequestEmailChange(BaseMutation):raise ValidationError({"redirect_url": error}, code=AccountErrorCode.INVALID.value)- channel_slug = clean_channel(channel, error_class=AccountErrorCode).slug+ channel_slug = clean_channel(+ channel, error_class=AccountErrorCode, allow_replica=False+ ).slugtoken_payload = {"old_email": user.email,diff --git a/saleor/graphql/account/mutations/account/send_confirmation_email.py b/saleor/graphql/account/mutations/account/send_confirmation_email.pyindex 838f9678e6..74434527bb 100644--- a/saleor/graphql/account/mutations/account/send_confirmation_email.py+++ b/saleor/graphql/account/mutations/account/send_confirmation_email.py@@ -99,7 +99,9 @@ class SendConfirmationEmail(BaseMutation):user = cls.clean_user(site, redirect_url, info)channel = clean_channel(- data.get("channel"), error_class=SendConfirmationEmailErrorCode+ data.get("channel"),+ error_class=SendConfirmationEmailErrorCode,+ allow_replica=False,).slugmanager = get_plugin_manager_promise(info.context).get()token = default_token_generator.make_token(user)diff --git a/saleor/graphql/account/mutations/authentication/request_password_reset.py b/saleor/graphql/account/mutations/authentication/request_password_reset.pyindex 90de5443aa..9f8c9015fa 100644--- a/saleor/graphql/account/mutations/authentication/request_password_reset.py+++ b/saleor/graphql/account/mutations/authentication/request_password_reset.py@@ -117,7 +117,7 @@ class RequestPasswordReset(BaseMutation):if not user.is_staff:channel_slug = clean_channel(- channel_slug, error_class=AccountErrorCode+ channel_slug, error_class=AccountErrorCode, allow_replica=False).slugelif channel_slug is not None:channel_slug = validate_channel(diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.pyindex ed80f120d8..11ad34d4a9 100644--- a/saleor/graphql/account/mutations/base.py+++ b/saleor/graphql/account/mutations/base.py@@ -330,7 +330,7 @@ class BaseCustomerCreate(ModelMutation, I18nMixin):channel_slug = cleaned_input.get("channel")if not instance.is_staff:channel_slug = clean_channel(- channel_slug, error_class=AccountErrorCode+ channel_slug, error_class=AccountErrorCode, allow_replica=False).slugelif channel_slug is not None:channel_slug = validate_channel(diff --git a/saleor/graphql/channel/utils.py b/saleor/graphql/channel/utils.pyindex df8317eebc..705700cbe0 100644--- a/saleor/graphql/channel/utils.py+++ b/saleor/graphql/channel/utils.py@@ -11,21 +11,25 @@ from ...channel.utils import get_default_channelfrom ...shipping.models import ShippingZone-def get_default_channel_slug_or_graphql_error() -> SimpleLazyObject:+def get_default_channel_slug_or_graphql_error(+ allow_replica: bool = False,+) -> SimpleLazyObject:"""Return a default channel slug in lazy way or a GraphQL error.Utility to get the default channel in GraphQL query resolvers."""- return SimpleLazyObject(lambda: get_default_channel_or_graphql_error().slug)+ return SimpleLazyObject(+ lambda: get_default_channel_or_graphql_error(allow_replica).slug+ )-def get_default_channel_or_graphql_error() -> Channel:+def get_default_channel_or_graphql_error(allow_replica: bool = False) -> Channel:"""Return a default channel or a GraphQL error.Utility to get the default channel in GraphQL query resolvers."""try:- channel = get_default_channel()+ channel = get_default_channel(allow_replica)except (ChannelNotDefined, NoDefaultChannel) as e:raise GraphQLError(str(e))else:@@ -59,12 +63,13 @@ def validate_channel(channel_slug, error_class):def clean_channel(channel_slug,error_class,+ allow_replica: bool = False,):if channel_slug is not None:channel = validate_channel(channel_slug, error_class)else:try:- channel = get_default_channel()+ channel = get_default_channel(allow_replica)except ChannelNotDefined:raise ValidationError({diff --git a/saleor/graphql/checkout/mutations/checkout_create.py b/saleor/graphql/checkout/mutations/checkout_create.pyindex f757bb63e7..ead0c8656f 100644--- a/saleor/graphql/checkout/mutations/checkout_create.py+++ b/saleor/graphql/checkout/mutations/checkout_create.py@@ -383,7 +383,9 @@ class CheckoutCreate(ModelMutation, I18nMixin):cls, _root, info: ResolveInfo, /, *, input):channel_input = input.get("channel")- channel = clean_channel(channel_input, error_class=CheckoutErrorCode)+ channel = clean_channel(+ channel_input, error_class=CheckoutErrorCode, allow_replica=False+ )if channel:input["channel"] = channelresponse = super().perform_mutation(_root, info, input=input)diff --git a/saleor/graphql/core/connection.py b/saleor/graphql/core/connection.pyindex 904f29b120..449d1b61b7 100644--- a/saleor/graphql/core/connection.py+++ b/saleor/graphql/core/connection.py@@ -339,7 +339,10 @@ def create_connection_slice(else:queryset = iterable- queryset, sort_by = sort_queryset_for_connection(iterable=queryset, args=args)+ allow_replica = getattr(info.context, "allow_replica", False)+ queryset, sort_by = sort_queryset_for_connection(+ iterable=queryset, args=args, allow_replica=allow_replica+ )args["sort_by"] = sort_byslice = connection_from_queryset_slice(@@ -485,7 +488,7 @@ def filter_qs(filter_input["channel"] = (args.get("channel")or filter_channel- or get_default_channel_slug_or_graphql_error()+ or get_default_channel_slug_or_graphql_error(allow_replica))if isinstance(iterable, ChannelQsContext):diff --git a/saleor/graphql/menu/schema.py b/saleor/graphql/menu/schema.pyindex e2e6ca3d18..c1a4b39183 100644--- a/saleor/graphql/menu/schema.py+++ b/saleor/graphql/menu/schema.py@@ -78,7 +78,9 @@ class MenuQueries(graphene.ObjectType):@staticmethoddef resolve_menu(_root, info: ResolveInfo, *, channel=None, **data):if channel is None:- channel = get_default_channel_slug_or_graphql_error()+ channel = get_default_channel_slug_or_graphql_error(+ allow_replica=info.context.allow_replica+ )return resolve_menu(info, channel, data.get("id"), data.get("name"), data.get("slug"))@@ -86,7 +88,9 @@ class MenuQueries(graphene.ObjectType):@staticmethoddef resolve_menus(_root, info: ResolveInfo, *, channel=None, **kwargs):if channel is None:- channel = get_default_channel_slug_or_graphql_error()+ channel = get_default_channel_slug_or_graphql_error(+ allow_replica=info.context.allow_replica+ )qs = resolve_menus(info, channel)qs = filter_connection_queryset(qs, kwargs, allow_replica=info.context.allow_replica@@ -96,14 +100,18 @@ class MenuQueries(graphene.ObjectType):@staticmethoddef resolve_menu_item(_root, info: ResolveInfo, *, channel=None, id: str):if channel is None:- channel = get_default_channel_slug_or_graphql_error()+ channel = get_default_channel_slug_or_graphql_error(+ allow_replica=info.context.allow_replica+ )_, id = from_global_id_or_error(id, MenuItem)return resolve_menu_item(info, id, channel)@staticmethoddef resolve_menu_items(_root, info: ResolveInfo, *, channel=None, **kwargs):if channel is None:- channel = get_default_channel_slug_or_graphql_error()+ channel = get_default_channel_slug_or_graphql_error(+ allow_replica=info.context.allow_replica+ )menu_items = resolve_menu_items(info)qs = ChannelQsContext(qs=menu_items, channel_slug=channel)qs = filter_connection_queryset(diff --git a/saleor/graphql/order/resolvers.py b/saleor/graphql/order/resolvers.pyindex 57e8461b11..2173fc5e08 100644--- a/saleor/graphql/order/resolvers.py+++ b/saleor/graphql/order/resolvers.py@@ -58,7 +58,9 @@ def resolve_draft_orders(info):def resolve_orders_total(info, period, channel_slug):database_connection_name = get_database_connection_name(info.context)if channel_slug is None:- channel_slug = get_default_channel_slug_or_graphql_error()+ channel_slug = get_default_channel_slug_or_graphql_error(+ allow_replica=info.context.allow_replica+ )channel = (Channel.objects.using(database_connection_name).filter(slug=str(channel_slug))diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.pyindex 21adae5174..5757a4ada5 100644--- a/saleor/graphql/product/schema.py+++ b/saleor/graphql/product/schema.py@@ -371,7 +371,9 @@ class ProductQueries(graphene.ObjectType):requestor, ALL_PRODUCTS_PERMISSIONS)if channel is None and not has_required_permissions:- channel = get_default_channel_slug_or_graphql_error()+ channel = get_default_channel_slug_or_graphql_error(+ allow_replica=info.context.allow_replica+ )if id:_, id = from_global_id_or_error(id, Collection)collection = resolve_collection_by_id(info, id, channel, requestor)@@ -392,7 +394,9 @@ class ProductQueries(graphene.ObjectType):requestor, ALL_PRODUCTS_PERMISSIONS)if channel is None and not has_required_permissions:- channel = get_default_channel_slug_or_graphql_error()+ channel = get_default_channel_slug_or_graphql_error(+ allow_replica=info.context.allow_replica+ )qs = resolve_collections(info, channel)kwargs["channel"] = channelqs = filter_connection_queryset(@@ -433,7 +437,9 @@ class ProductQueries(graphene.ObjectType):)if channel is None and not has_required_permissions:- channel = get_default_channel_slug_or_graphql_error()+ channel = get_default_channel_slug_or_graphql_error(+ allow_replica=info.context.allow_replica+ )product = resolve_product(info,@@ -457,7 +463,9 @@ class ProductQueries(graphene.ObjectType):requestor, ALL_PRODUCTS_PERMISSIONS)if channel is None and not has_required_permissions:- channel = get_default_channel_slug_or_graphql_error()+ channel = get_default_channel_slug_or_graphql_error(+ allow_replica=info.context.allow_replica+ )qs = resolve_products(info, requestor, channel_slug=channel)if search:qs = ChannelQsContext(@@ -502,7 +510,9 @@ class ProductQueries(graphene.ObjectType):)if channel is None and not has_required_permissions:- channel = get_default_channel_slug_or_graphql_error()+ channel = get_default_channel_slug_or_graphql_error(+ allow_replica=info.context.allow_replica+ )variant = resolve_variant(info,@@ -525,7 +535,9 @@ class ProductQueries(graphene.ObjectType):requestor, ALL_PRODUCTS_PERMISSIONS)if channel is None and not has_required_permissions:- channel = get_default_channel_slug_or_graphql_error()+ channel = get_default_channel_slug_or_graphql_error(+ allow_replica=info.context.allow_replica+ )qs = resolve_product_variants(info,ids=ids,diff --git a/saleor/graphql/product/types/categories.py b/saleor/graphql/product/types/categories.pyindex 4ae8420f38..1ba3787b2a 100644--- a/saleor/graphql/product/types/categories.py+++ b/saleor/graphql/product/types/categories.py@@ -172,7 +172,9 @@ class Category(ModelObjectType[models.Category]):)tree = root.get_descendants(include_self=True)if channel is None and not has_required_permissions:- channel = get_default_channel_slug_or_graphql_error()+ channel = get_default_channel_slug_or_graphql_error(+ allow_replica=info.context.allow_replica+ )connection_name = get_database_connection_name(info.context)qs = models.Product.objects.using(connection_name).all()if not has_required_permissions:diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex a1a4f38f5e..6322671a2b 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -1823,7 +1823,9 @@ class ProductType(ModelObjectType[models.ProductType]):def resolve_products(root: models.ProductType, info, *, channel=None, **kwargs):requestor = get_user_or_app_from_context(info.context)if channel is None:- channel = get_default_channel_slug_or_graphql_error()+ channel = get_default_channel_slug_or_graphql_error(+ allow_replica=info.context.allow_replica+ )qs = root.products.using(get_database_connection_name(info.context)).visible_to_user(requestor, channel)diff --git a/saleor/graphql/utils/sorting.py b/saleor/graphql/utils/sorting.pyindex 125bacdd9a..c0fedd4ee5 100644--- a/saleor/graphql/utils/sorting.py+++ b/saleor/graphql/utils/sorting.py@@ -24,7 +24,7 @@ def _sort_queryset_by_attribute(queryset, sorting_attribute, sorting_direction):return queryset-def sort_queryset_for_connection(iterable, args):+def sort_queryset_for_connection(iterable, args, allow_replica):sort_by = args.get("sort_by")reversed = True if "last" in args else Falseif sort_by:@@ -33,7 +33,7 @@ def sort_queryset_for_connection(iterable, args):sort_by=sort_by,reversed=reversed,channel_slug=args.get("channel") # type: ignore[arg-type]- or get_default_channel_slug_or_graphql_error(),+ or get_default_channel_slug_or_graphql_error(allow_replica=allow_replica),)else:iterable, sort_by = sort_queryset_by_default(