Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add more usages of allow_writer context manager (#15749)
Marcin Gębala52b3886bef42
diff --git a/saleor/graphql/executor.py b/saleor/graphql/executor.pynew file mode 100644index 0000000000..ddafe3a2e9--- /dev/null+++ b/saleor/graphql/executor.py@@ -0,0 +1,23 @@+from graphql.execution import executor++original_complete_value_catching_error = executor.complete_value_catching_error+++def _patched_complete_value_catching_error(*args, **kwargs):+ info = args[3]+ from saleor.core.db.connection import allow_writer_in_context++ with allow_writer_in_context(info.context):+ return original_complete_value_catching_error(*args, **kwargs)+++def patch_executor():+ """Patch `complete_value_catching_error` function to allow writer DB in mutations.++ The `complete_value_catching_error` function is called when resolving a field in+ GraphQL. This patch wraps each call with `allow_writer_in_context` context manager.+ This allows to use writer DB in resolvers, when they are called via mutation, while+ they will still raise or log error when a resolver is run in a query.+ """++ executor.complete_value_catching_error = _patched_complete_value_catching_errordiff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex 9ae90c1e61..169eb88169 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -14,6 +14,7 @@ from prices import TaxedMoneyfrom ..channel.models import Channelfrom ..checkout import base_calculations+from ..core.db.connection import allow_writerfrom ..core.models import EventDeliveryfrom ..core.payments import PaymentInterfacefrom ..core.prices import quantize_price@@ -2219,4 +2220,8 @@ def get_plugins_manager(requestor_getter: Optional[Callable[[], "Requestor"]] = None,) -> PluginsManager:with opentracing.global_tracer().start_active_span("get_plugins_manager"):- return PluginsManager(settings.PLUGINS, requestor_getter, allow_replica)+ if allow_replica:+ return PluginsManager(settings.PLUGINS, requestor_getter, allow_replica)+ else:+ with allow_writer():+ return PluginsManager(settings.PLUGINS, requestor_getter, allow_replica)diff --git a/saleor/plugins/webhook/tests/test_shipping_webhook.py b/saleor/plugins/webhook/tests/test_shipping_webhook.pyindex b3c30d81e1..7e1f5bb3dc 100644--- a/saleor/plugins/webhook/tests/test_shipping_webhook.py+++ b/saleor/plugins/webhook/tests/test_shipping_webhook.py@@ -412,9 +412,10 @@ def test_order_available_shipping_methods():# givensettings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ shipping_method = order_with_lines.shipping_methoddef respond(*args, **kwargs):- return webhook_response(order_with_lines.shipping_method)+ return webhook_response(shipping_method)mocked_webhook.side_effect = respondpermission_group_manage_orders.user_set.add(staff_api_client.user)diff --git a/saleor/product/utils/digital_products.py b/saleor/product/utils/digital_products.pyindex d6f604a37a..913ed1ff0c 100644--- a/saleor/product/utils/digital_products.py+++ b/saleor/product/utils/digital_products.py@@ -4,6 +4,7 @@ from django.contrib.sites.models import Sitefrom django.utils.timezone import nowfrom ...account import events as account_events+from ...core.db.connection import allow_writerfrom ..models import DigitalContentUrl@@ -42,6 +43,7 @@ def digital_content_url_is_valid(content_url: DigitalContentUrl) -> bool:return True+@allow_writer()def increment_download_count(content_url: DigitalContentUrl):content_url.download_num += 1content_url.save(update_fields=["download_num"])diff --git a/saleor/product/views.py b/saleor/product/views.pyindex cc75fcdac6..75c82ec118 100644--- a/saleor/product/views.py+++ b/saleor/product/views.py@@ -2,6 +2,7 @@ import mimetypesimport osfrom typing import Union+from django.conf import settingsfrom django.http import FileResponse, HttpResponseNotFoundfrom django.shortcuts import get_object_or_404@@ -15,7 +16,9 @@ from .utils.digital_products import (def digital_product(request, token: str) -> Union[FileResponse, HttpResponseNotFound]:"""Return the direct download link to content if given token is still valid."""- qs = DigitalContentUrl.objects.prefetch_related("line__order__user")+ qs = DigitalContentUrl.objects.using(+ settings.DATABASE_CONNECTION_REPLICA_NAME+ ).prefetch_related("line__order__user")content_url = get_object_or_404(qs, token=token) # type: DigitalContentUrlif not digital_content_url_is_valid(content_url):return HttpResponseNotFound("Url is not valid anymore")diff --git a/saleor/settings.py b/saleor/settings.pyindex e0acb03a38..b69ebaecc3 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -29,6 +29,7 @@ from sentry_sdk.integrations.logging import ignore_loggerfrom . import PatchedSubscriberExecutionContext, __version__from .core.languages import LANGUAGES as CORE_LANGUAGESfrom .core.schedules import initiated_promotion_webhook_schedule+from .graphql.executor import patch_executordjango_stubs_ext.monkeypatch()@@ -878,6 +879,8 @@ PRODUCT_MAX_INDEXED_VARIANTS = 1000executor.SubscriberExecutionContext = PatchedSubscriberExecutionContext # type: ignore+patch_executor()+# Optional queue names for Celery tasks.# Set None to route to the default queue, or a string value to use a separate one#