repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
saleor
saleor/product/utils/__init__.py
.py
import datetime from collections.abc import Iterable from typing import TYPE_CHECKING from uuid import UUID from ...core.taxes import TaxedMoney, zero_taxed_money from ...core.tracing import traced_atomic_transaction from ...core.utils.events import call_event from ...discount.utils.promotion import mark_active_catalo...
86
3,351
saleor
saleor/product/utils/product.py
.py
from collections import defaultdict from django.conf import settings from django.db import transaction from django.db.models import Exists, OuterRef, QuerySet from ...discount.models import PromotionRule from ...product.models import ProductChannelListing from ..models import ProductVariant def get_channel_to_produ...
137
5,318
saleor
saleor/product/utils/tasks_utils.py
.py
from typing import IO from PIL import Image, UnidentifiedImageError from requests.exceptions import HTTPError from ...core.utils import create_file_from_response from ...core.utils.validators import is_valid_image_content_type from ...thumbnail.utils import ProcessedImage, get_filename_from_url def validate_status_...
60
1,786
saleor
saleor/product/utils/variant_prices.py
.py
from collections import defaultdict from decimal import Decimal from typing import cast from uuid import UUID from django.conf import settings from django.db import transaction from django.db.models import Exists, OuterRef from prices import Money from ...channel.models import Channel from ...core.taxes import zero_m...
364
14,254
saleor
saleor/product/utils/search_helpers.py
.py
from ..tasks import mark_products_search_vector_as_dirty # Results in update time ~0.2s, consumes ~30 MB MARK_SEARCH_VECTOR_DIRTY_BATCH_SIZE = 1000 def mark_products_search_vector_as_dirty_in_batches(product_ids: list[int]): """Mark products as needing search index updates.""" for i in range(0, len(product_i...
12
502
saleor
saleor/product/utils/availability.py
.py
from dataclasses import dataclass from decimal import Decimal from typing import Literal from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange from ...product.models import ProductChannelListing, ProductVariantChannelListing from ...tax import TaxCalculationStrategy from ...tax.calculations import calcula...
229
7,274
saleor
saleor/account/throttling.py
.py
import datetime import logging from math import ceil from django.core.cache import cache from django.core.exceptions import ValidationError from django.utils import timezone from ..core.utils import get_client_ip from . import models from .error_codes import AccountErrorCode from .utils import retrieve_user_by_email ...
146
4,691
saleor
saleor/account/notifications.py
.py
from urllib.parse import urlencode from ..core.notification.utils import get_site_context from ..core.notify import NotifyEventType, NotifyHandler from ..core.tokens import ( account_confirm_token_generator, account_delete_token_generator, password_reset_token_generator, ) from ..core.utils.url import prep...
205
6,762
saleor
saleor/account/utils.py
.py
from dataclasses import dataclass from typing import TYPE_CHECKING from django.conf import settings from django.db.models import Exists, F, OuterRef from ..app.models import App from ..checkout import AddressType from ..core.tracing import traced_atomic_transaction from ..core.utils.events import call_event from ..pe...
207
6,830
saleor
saleor/account/lock_objects.py
.py
from .models import CustomerType, User def user_qs_select_for_update(): return User.objects.order_by("pk").select_for_update(of=("self",)) def customer_type_qs_select_for_update(): return CustomerType.objects.order_by("pk").select_for_update(of=("self",))
10
268
saleor
saleor/account/exceptions.py
.py
class NoDefaultCustomerType(Exception): def __init__(self, msg=None): if msg is None: msg = "The default customer type does not exist." super().__init__(msg)
6
190
saleor
saleor/account/error_codes.py
.py
from enum import Enum class AccountErrorCode(Enum): ACTIVATE_OWN_ACCOUNT = "activate_own_account" ACTIVATE_SUPERUSER_ACCOUNT = "activate_superuser_account" DUPLICATED_INPUT_ITEM = "duplicated_input_item" DEACTIVATE_OWN_ACCOUNT = "deactivate_own_account" DEACTIVATE_SUPERUSER_ACCOUNT = "deactivate_s...
116
3,958
saleor
saleor/account/models.py
.py
from collections.abc import Iterable from functools import partial from uuid import uuid4 from django.conf import settings from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.contrib.postgres.indexes import BTreeIndex, GinIndex from django.contrib.postgres.search import SearchVector...
482
17,590
saleor
saleor/account/apps.py
.py
from django.apps import AppConfig from django.db.models.signals import post_delete class AccountAppConfig(AppConfig): name = "saleor.account" def ready(self): from .models import User from .signals import delete_avatar post_delete.connect( delete_avatar, sende...
17
385
saleor
saleor/account/i18n.py
.py
import logging from collections import defaultdict import i18naddress from django import forms from django.core.exceptions import ValidationError from django.forms import BoundField from django.forms.models import ModelFormMetaclass from django_countries import countries from .i18n_valid_address_extension import VALI...
344
12,214
saleor
saleor/account/__init__.py
.py
class CustomerEvents: """The different customer event types.""" # Account related events ACCOUNT_CREATED = "account_created" ACCOUNT_ACTIVATED = "account_activated" ACCOUNT_DEACTIVATED = "account_deactivated" PASSWORD_RESET_LINK_SENT = "password_reset_link_sent" PASSWORD_RESET = "password_r...
43
1,928
saleor
saleor/account/i18n_valid_address_extension.py
.py
from enum import Enum from ..graphql.account.enums import CountryCodeEnum class AddressFieldsToSubstitute(Enum): CITY_AREA = "city_area" COUNTRY_AREA = "country_area" IE_COUNTRY_AREA = { "Carlow": "Co. Carlow", "Cavan": "Co. Cavan", "Clare": "Co. Clare", "Cork": "Co. Cork", "Donegal": "...
46
1,216
saleor
saleor/account/signals.py
.py
from ..core.tasks import delete_from_storage_task def delete_avatar(sender, instance, **kwargs): if avatar := instance.avatar: delete_from_storage_task.delay(avatar.name)
7
185
saleor
saleor/account/search.py
.py
from typing import TYPE_CHECKING from django.db.models import Value, prefetch_related_objects from ..core.postgres import FlatConcatSearchVector, NoValidationSearchVector if TYPE_CHECKING: from .models import Address, User USER_SEARCH_FIELDS = [ "email", "first_name", "last_name", ] def update_use...
144
4,615
saleor
saleor/account/i18n_rules_override.py
.py
import i18naddress original_load_validation_data = i18naddress.load_validation_data COUNTRIES_RULES_OVERRIDE = { "JP": { # Library `google-i18n-address` use `AddressValidationMetadata` form Google to provide required fields. # During address normalization, unexpected or unnecessary fields are rem...
29
1,115
saleor
saleor/account/forms.py
.py
from phonenumbers.phonenumberutil import country_code_for_region from .i18n import AddressMetaForm, get_address_form_class def get_address_form( data, country_code, initial=None, instance=None, enable_normalization=True, **kwargs ): country_form = AddressMetaForm(data, initial=initial) if country_form.is...
37
1,294
saleor
saleor/account/widgets.py
.py
from django.forms import Select class DatalistTextWidget(Select): input_type = "text" def get_context(self, *args): context = super().get_context(*args) context["widget"]["type"] = self.input_type return context def format_value(self, value): value = super().format_value(...
15
351
saleor
saleor/account/tasks.py
.py
import logging from typing import cast from urllib.parse import urlencode from django.utils import timezone from ..celeryconf import app from ..core.db.connection import allow_writer from ..core.tokens import ( account_confirm_token_generator, password_reset_token_generator, ) from ..core.utils.events import ...
123
3,507
saleor
saleor/account/validators.py
.py
from django.core.exceptions import ValidationError from phonenumber_field.phonenumber import to_python from phonenumbers.phonenumberutil import is_possible_number from .error_codes import AccountErrorCode def validate_possible_number(phone, country=None): phone_number = to_python(phone, country) if ( ...
20
597
saleor
saleor/account/events.py
.py
from ..app.models import App from ..order.models import Order from . import CustomerEvents from .models import CustomerEvent, User def customer_account_created_event(*, user: User) -> CustomerEvent | None: return CustomerEvent.objects.create(user=user, type=CustomerEvents.ACCOUNT_CREATED) def customer_account_a...
114
3,393
saleor
saleor/account/management/commands/createsuperuser.py
.py
# mypy: ignore-errors """Management utility to create superusers. This module was moved for Django Auth directly to Saleor. """ import getpass import os import sys from django.contrib.auth.password_validation import validate_password from django.core import exceptions from django.core.management.base import BaseComm...
285
12,137
saleor
saleor/account/management/commands/changepassword.py
.py
from django.contrib.auth.management.commands.changepassword import Command __all__ = ["Command"]
4
98
saleor
saleor/account/tests/test_notifications.py
.py
from unittest import mock from urllib.parse import urlencode import pytest from ...core.notify import NotifyEventType, UserNotifyEvent from ...core.tests.utils import get_site_context_payload from ...core.utils.url import prepare_url from ...graphql.core.utils import to_global_id_or_none from ...plugins.manager impor...
151
5,047
saleor
saleor/account/tests/test_account_command.py
.py
import os from unittest import mock from django.core.management import call_command from ..models import Group, User def test_createsuperuser_command(db): # given # when call_command("createsuperuser", email="testAdmin@example.com", interactive=False) # then assert User.objects.count() == 1 ...
54
1,422
saleor
saleor/account/tests/test_account.py
.py
from unittest.mock import patch from urllib.parse import urlencode import i18naddress import pytest from django.core.exceptions import ValidationError from django.http import QueryDict from django_countries.fields import Country from ...order.models import Order from .. import forms, i18n from ..i18n_valid_address_ex...
443
13,193
saleor
saleor/account/tests/test_search.py
.py
from ..search import update_user_search_vector def test_update_user_search_vector(customer_user, address, address_usa): # given customer_user.addresses.set((address, address_usa)) customer_user.search_vector = None # when update_user_search_vector(customer_user) # then customer_user.refr...
42
1,155
saleor
saleor/account/tests/test_throttling.py
.py
import datetime import logging from unittest.mock import patch import pytest from django.core.exceptions import ValidationError from django.utils import timezone from freezegun import freeze_time from ...tests import race_condition from ..error_codes import AccountErrorCode from ..throttling import ( MAX_DELAY, ...
409
13,554
saleor
saleor/account/tests/test_customer_type.py
.py
import pytest from django.db import IntegrityError from django.db.models.deletion import ProtectedError from ..exceptions import NoDefaultCustomerType from ..migrations.tasks.saleor3_23 import assign_default_customer_type_to_users_task from ..models import CustomerType, User from ..utils import get_default_customer_ty...
143
4,315
saleor
saleor/account/tests/test_utils.py
.py
from unittest.mock import patch import pytest from django.test import override_settings from ...checkout import AddressType from ...plugins.manager import get_plugins_manager from ..models import Address, User from ..utils import ( get_user_groups_permissions, is_user_address_limit_reached, remove_the_old...
333
11,053
saleor
saleor/account/tests/fixtures/user.py
.py
from typing import Any import pytest from ....account.models import Group, User, UserManager from ....permission.enums import get_permissions from .customer_type import get_or_create_default_customer_type def dangerously_get_or_create_superuser( email: str, password: str | None = None, **extra_fields: Any ) -> ...
159
5,025
saleor
saleor/account/tests/fixtures/customer_type.py
.py
import pytest from ...models import CustomerType __all__ = [ "customer_type", "customer_type_with_attributes", "default_customer_type", "get_or_create_default_customer_type", ] def get_or_create_default_customer_type() -> CustomerType: # Transactional tests (django_db(transaction=True)) flush al...
47
1,236
saleor
saleor/translations/error_codes.py
.py
from enum import Enum class AttributeTranslateErrorCode(Enum): GRAPHQL_ERROR = "graphql_error" INVALID = "invalid" NOT_FOUND = "not_found" REQUIRED = "required" class AttributeValueTranslateErrorCode(Enum): GRAPHQL_ERROR = "graphql_error" INVALID = "invalid" NOT_FOUND = "not_found" R...
30
658
saleor
saleor/tax/utils.py
.py
import logging from collections import defaultdict from collections.abc import Iterable from decimal import Decimal from typing import TYPE_CHECKING, Optional from django.conf import settings from prices import TaxedMoney from ..core.utils.country import get_active_country from ..tax.models import TaxClass, TaxClassC...
403
14,348
saleor
saleor/tax/error_codes.py
.py
from enum import Enum class TaxExemptionManageErrorCode(Enum): GRAPHQL_ERROR = "graphql_error" INVALID = "invalid" NOT_FOUND = "not_found" NOT_EDITABLE_ORDER = "not_editable_order" class TaxConfigurationUpdateErrorCode(Enum): DUPLICATED_INPUT_ITEM = "duplicated_input_item" GRAPHQL_ERROR = "g...
49
1,251
saleor
saleor/tax/models.py
.py
from django.conf import settings from django.db import models from django_countries.fields import CountryField from ..channel.models import Channel from ..core.models import ModelWithMetadata from . import TaxCalculationStrategy class TaxClass(ModelWithMetadata): name = models.CharField(max_length=255) clas...
91
3,130
saleor
saleor/tax/__init__.py
.py
class TaxCalculationStrategy: FLAT_RATES = "FLAT_RATES" TAX_APP = "TAX_APP" CHOICES = [(FLAT_RATES, "Flat rates"), (TAX_APP, "Tax app")] class TaxableObjectDiscountType: SUBTOTAL = "SUBTOTAL" SHIPPING = "SHIPPING" CHOICES = [(SUBTOTAL, "Subtotal"), (SHIPPING, "Shipping")]
13
301
saleor
saleor/tax/webhooks/parser.py
.py
import logging from typing import Any from pydantic import ValidationError from ...core.taxes import TAX_ERROR_FIELD_LENGTH, TaxData, TaxDataError, TaxLineData from ...core.utils.text import safe_truncate from ...webhook.response_schemas.taxes import CalculateTaxesSchema from ...webhook.response_schemas.utils.helpers...
53
1,764
saleor
saleor/tax/webhooks/shared.py
.py
import logging from typing import TYPE_CHECKING, Any, Union from django.conf import settings from promise import Promise from ...app.models import App from ...core.taxes import TaxData, TaxDataError from ...webhook.transport.synchronous.transport import ( trigger_webhook_sync_promise, ) from ...webhook.utils impo...
140
4,301
saleor
saleor/tax/calculations/__init__.py
.py
from decimal import Decimal from prices import Money, TaxedMoney from ...core.prices import quantize_price def calculate_flat_rate_tax( money: "Money", tax_rate: "Decimal", prices_entered_with_tax: bool ) -> TaxedMoney: currency = money.currency tax_rate = Decimal(1 + tax_rate / 100) if prices_ente...
47
1,411
saleor
saleor/tax/calculations/order.py
.py
from collections import defaultdict from collections.abc import Iterable from decimal import Decimal from typing import TYPE_CHECKING, cast from django.conf import settings from prices import TaxedMoney from ...core.prices import quantize_price from ...core.taxes import zero_taxed_money from ...order import base_calc...
190
6,652
saleor
saleor/tax/calculations/checkout.py
.py
from decimal import Decimal from typing import TYPE_CHECKING from django.conf import settings from prices import TaxedMoney from ...checkout import base_calculations from ...core.prices import quantize_price from ...core.taxes import zero_taxed_money from ..models import TaxClassCountryRate from ..utils import ( ...
118
3,682
saleor
saleor/tax/tests/test_order_calculations.py
.py
from decimal import Decimal import pytest from prices import Money, TaxedMoney from saleor.tax.models import TaxClass, TaxClassCountryRate from ...core.prices import quantize_price from ...core.taxes import zero_money, zero_taxed_money from ...discount import DiscountType, DiscountValueType from ...order import Orde...
906
27,723
saleor
saleor/tax/tests/test_checkout_calculations.py
.py
from decimal import Decimal from unittest import mock import pytest from prices import Money, TaxedMoney from ...checkout import calculations from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines from ...checkout.tests.utils import add_variant_to_checkout from ...core.prices import quantize_price fr...
1,487
47,301
saleor
saleor/tax/tests/test_calculations.py
.py
from decimal import Decimal import pytest from prices import Money from ...core.prices import quantize_price from ..calculations import calculate_flat_rate_tax @pytest.mark.parametrize( ("amount", "net", "gross", "rate", "prices_entered_with_tax"), [ ("10.00", "10.00", "12.30", Decimal(23), False), ...
23
778
saleor
saleor/tax/tests/test_utils.py
.py
from decimal import Decimal from unittest.mock import Mock import pytest from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines from ...core.prices import Money, TaxedMoney from ...core.utils.country import get_active_country from ...graphql.tax.enums import TaxCalculationStrategy from ...order.utils...
440
14,378
saleor
saleor/tax/tests/webhooks/test_shared.py
.py
import json from unittest import mock import graphene import pytest from saleor.core.taxes import TaxDataError from ....core import EventDeliveryStatus from ....core.models import EventDelivery from ....webhook.event_types import WebhookEventSyncType from ....webhook.models import Webhook, WebhookEvent from ...webho...
433
13,861
saleor
saleor/tax/tests/webhooks/test_parser.py
.py
import pytest from ....core.taxes import TaxData, TaxDataError from ....webhook.event_types import WebhookEventSyncType from ...webhooks.parser import parse_tax_data def test_parse_tax_data_success(tax_data_response): # given line_count = len(tax_data_response["lines"]) # when tax_data = parse_tax_d...
66
1,774
saleor
saleor/tax/tests/fixtures/utils.py
.py
from ....tax import TaxCalculationStrategy from ....tax.models import TaxConfiguration def create_channel_tax_configuration(channel): # Use TAX_APP strategy, to enable calculations with plugins by default. tax_configuration = TaxConfiguration.objects.create( channel=channel, metadata={"key": "...
21
727
saleor
saleor/tax/tests/fixtures/tax_class.py
.py
import pytest from django_countries import countries from ....plugins.avatax import ( DEFAULT_TAX_CODE, META_CODE_KEY, META_DESCRIPTION_KEY, TAX_CODE_NON_TAXABLE_PRODUCT, ) from ...models import TaxClass, TaxClassCountryRate @pytest.fixture(autouse=True) def default_tax_class(db): tax_class, _ = ...
75
2,131
saleor
saleor/attribute/utils.py
.py
from collections import defaultdict from collections.abc import Iterable from django.db import transaction from django.db.models import Exists, OuterRef, Q from ..account.models import User from ..page.models import Page from ..product.models import Product, ProductVariant from . import AttributeInputType from .lock_...
297
10,661
saleor
saleor/attribute/lock_objects.py
.py
from django.db.models import QuerySet from .models.base import Attribute, AttributeValue def attribute_value_qs_select_for_update() -> QuerySet[AttributeValue]: # Matching lock order (sort_order, pk) of `perform_reordering` to avoid deadlocks. # TODO: switch to a stable pk-only ordering together with the reo...
24
833
saleor
saleor/attribute/error_codes.py
.py
from enum import Enum class AttributeErrorCode(Enum): ALREADY_EXISTS = "already_exists" GRAPHQL_ERROR = "graphql_error" INVALID = "invalid" NOT_FOUND = "not_found" REQUIRED = "required" UNIQUE = "unique" class AttributeBulkCreateErrorCode(Enum): ALREADY_EXISTS = "already_exists" BLAN...
35
870
saleor
saleor/attribute/__init__.py
.py
class AttributeInputType: """The type that we expect to render the attribute's values as.""" DROPDOWN = "dropdown" MULTISELECT = "multiselect" FILE = "file" REFERENCE = "reference" SINGLE_REFERENCE = "single-reference" NUMERIC = "numeric" RICH_TEXT = "rich-text" PLAIN_TEXT = "plain-...
130
3,439
saleor
saleor/attribute/search.py
.py
from typing import Union from django.db.models import QuerySet, Value from ..attribute import AttributeInputType from ..core.editorjs import editorjs_to_text from ..core.postgres import NoValidationSearchVector from .models import Attribute, AttributeValue def get_search_vectors_for_attribute_values( attribute:...
94
3,152
saleor
saleor/attribute/management/commands/update_attribute_file_urls.py
.py
import logging import re from urllib.parse import urlparse from botocore.exceptions import ClientError from django.conf import settings from django.core.management.base import BaseCommand, CommandError from ....core.storages import S3MediaStorage from ...models import AttributeValue logger = logging.getLogger(__name...
57
2,100
saleor
saleor/attribute/tests/model_helpers.py
.py
from django.db.models.expressions import Exists, OuterRef from ...page.models import Page from ...product.models import Product from ..models import ( AssignedPageAttributeValue, AssignedProductAttributeValue, Attribute, AttributePage, AttributeProduct, AttributeValue, ) def get_page_attribut...
63
2,093
saleor
saleor/attribute/tests/test_utils.py
.py
import pytest from ...attribute.models import AssignedPageAttributeValue from ...product.models import ProductType from .. import AttributeInputType, AttributeType from ..models import Attribute, AttributeValue from ..utils import ( associate_attribute_values_to_instance, validate_attribute_owns_values, ) from...
288
9,664
saleor
saleor/attribute/tests/fixtures/translation.py
.py
import pytest from ....tests.utils import dummy_editorjs from ...models import AttributeTranslation, AttributeValueTranslation from ...utils import associate_attribute_values_to_instance @pytest.fixture def translated_attribute(product): attribute = product.product_type.product_attributes.first() return Attr...
68
2,357
saleor
saleor/attribute/tests/fixtures/attribute.py
.py
import datetime import pytest from ....core.editorjs import editorjs_to_text from ....core.units import MeasurementUnits from ....core.utils.text import safe_truncate from ....tests.utils import dummy_editorjs from ... import AttributeEntityType, AttributeInputType, AttributeType from ...models import Attribute, Attr...
981
29,002
saleor
saleor/attribute/tests/models/test_base.py
.py
from saleor.attribute import AttributeType from saleor.attribute.models import Attribute, AttributeValue def test_attribute_value_setting_up_max_sort_order(): # given attribute = Attribute.objects.create( slug="test-slug", name="test name", type=AttributeType.PRODUCT_TYPE, ) as...
179
4,800
saleor
saleor/attribute/models/customer.py
.py
from django.contrib.postgres.indexes import BTreeIndex from django.db import models from ...account.models import CustomerType, User from ...core.models import SortableModel from .base import AssociatedAttributeManager class AssignedUserAttributeValue(SortableModel): value = models.ForeignKey( "Attribute...
49
1,439
saleor
saleor/attribute/models/__init__.py
.py
from .base import ( Attribute, AttributeTranslation, AttributeValue, AttributeValueTranslation, ) from .customer import AssignedUserAttributeValue, AttributeCustomerType from .page import AssignedPageAttributeValue, AttributePage from .product import AssignedProductAttributeValue, AttributeProduct from ...
31
822
saleor
saleor/attribute/models/product.py
.py
from django.contrib.postgres.indexes import BTreeIndex from django.db import models from ...core.models import SortableModel from ...product.models import Product, ProductType from .base import AssociatedAttributeManager class AssignedProductAttributeValue(SortableModel): value = models.ForeignKey( "Attr...
51
1,461
saleor
saleor/attribute/models/page.py
.py
from django.contrib.postgres.indexes import BTreeIndex from django.db import models from ...core.models import SortableModel from ...page.models import Page, PageType from .base import AssociatedAttributeManager class AssignedPageAttributeValue(SortableModel): value = models.ForeignKey( "AttributeValue",...
49
1,384
saleor
saleor/attribute/models/product_variant.py
.py
from django.db import models from ...core.models import SortableModel from ...product.models import ProductType, ProductVariant from .base import AssociatedAttributeManager, AttributeValue, BaseAssignedAttribute class AssignedVariantAttributeValue(SortableModel): value = models.ForeignKey( "AttributeValu...
79
2,420
saleor
saleor/attribute/models/base.py
.py
from typing import TYPE_CHECKING, TypeVar, Union from django.contrib.postgres.indexes import BTreeIndex, GinIndex from django.db import models, transaction from django.db.models import Case, Exists, F, OrderBy, OuterRef, Q, Value, When from ...account.models import CustomerType from ...core.db.fields import Sanitized...
583
21,778
saleor
saleor/graphql/middleware.py
.py
from .views import GraphQLView def process_view(self, request, view_func, *args): if hasattr(view_func, "view_class") and issubclass( view_func.view_class, GraphQLView ): request._graphql_view = True
9
226
saleor
saleor/graphql/error.py
.py
from django.core.exceptions import ValidationError from graphql.error import GraphQLError from pydantic import ValidationError as PydanticValidationError def pydantic_to_validation_error( exc: PydanticValidationError, default_error_code: str = "invalid" ) -> ValidationError: """Convert Pydantic ValidationErro...
68
2,569
saleor
saleor/graphql/promise.py
.py
from promise import Promise def __del_promise__(self: Promise) -> None: # Clean up references to break up any reference cycles self._handlers = None # type: ignore[assignment] self._fulfillment_handler0 = None self._rejection_handler0 = None self._promise0 = None self._future = None # type: ...
23
825
saleor
saleor/graphql/__init__.py
.py
from typing import Any, NotRequired, TypedDict class GraphQLOperationResult(TypedDict): data: NotRequired[dict[str, Any] | None] errors: NotRequired[list[dict[str, Any]] | None] extensions: NotRequired[dict[str, dict] | None]
8
240
saleor
saleor/graphql/schema_printer.py
.py
"""Code ported from GraphQL Core 3.0. Can be dropped once we upgrade from the legacy version of GraphQL Core. """ from collections.abc import Callable from typing import cast from graphene.types.definitions import GrapheneObjectType from graphql.language.printer import print_ast from graphql.type.definition import (...
499
15,952
saleor
saleor/graphql/views.py
.py
import decimal import hashlib import importlib import time from inspect import isclass from typing import Any, cast from urllib.parse import urljoin import orjson from django.conf import settings from django.core.cache import cache from django.core.exceptions import RequestDataTooBig from django.http import HttpReques...
686
27,159
saleor
saleor/graphql/context.py
.py
from typing import cast from django.contrib.auth import authenticate from django.http import HttpRequest from django.utils import timezone from django.utils.functional import SimpleLazyObject from ..account.models import User from ..app.models import App from ..core.auth import get_token_from_request from ..core.jwt ...
97
3,530
saleor
saleor/graphql/metrics.py
.py
import time from collections.abc import Iterator from contextlib import AbstractContextManager, contextmanager from django.conf import settings from opentelemetry.semconv._incubating.attributes import graphql_attributes from opentelemetry.semconv.attributes import error_attributes from opentelemetry.util.types import ...
212
6,127
saleor
saleor/graphql/query_cost_map.py
.py
"""Costs map used by query complexity validator. It's three levels deep dict of dicts: - Type - Fields - Complexity To set complexity cost for querying a field "likes" on type "User": { "User": { "likes": {"complexity": 2} } } Querying above field will not increase query complexity by 1. If field'...
455
16,735
saleor
saleor/graphql/decorators.py
.py
from collections.abc import Iterable from enum import Enum from functools import wraps from graphene import ResolveInfo from ..attribute import AttributeType from ..attribute.models import Attribute from ..core.exceptions import PermissionDenied from ..permission.auth_filters import is_app, is_staff_user from ..permi...
152
4,436
saleor
saleor/graphql/api.py
.py
from functools import partial, wraps import graphql from django.urls import reverse from django.utils.functional import SimpleLazyObject from graphql import ( GraphQLCachedBackend, GraphQLCoreBackend, GraphQLInterfaceType, GraphQLObjectType, GraphQLScalarType, GraphQLSchema, execute, pa...
260
8,119
saleor
saleor/graphql/storefront_traffic.py
.py
import warnings from django.conf import settings from django.contrib.sites.models import Site from django.core.cache import cache from jwt import InvalidTokenError from ..account.models import User from ..core.auth import get_token_from_request from ..site.models import SiteSettings from .core import SaleorContext S...
105
3,872
saleor
saleor/graphql/graphql_core.py
.py
from graphql.execution import executor from graphql.execution.base import ExecutionResult 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 ...
58
2,350
saleor
saleor/graphql/conftest.py
.py
import pytest from django.contrib.sites.models import Site from .storefront_traffic import set_allow_storefront_traffic_cache @pytest.fixture(autouse=True) def _warm_storefront_traffic_cache(): """Keep the storefront-traffic guard from adding DB queries per request. ``is_storefront_traffic_blocked`` resolve...
23
919
saleor
saleor/graphql/management/commands/get_graphql_schema.py
.py
from django.core.management.base import BaseCommand from ...api import schema from ...schema_printer import print_schema class Command(BaseCommand): help = "Writes SDL for GraphQL API schema to stdout" def handle(self, *args, **options): self.stdout.write(print_schema(schema))
12
298
saleor
saleor/graphql/product/utils.py
.py
from collections import defaultdict from collections.abc import Iterable from dataclasses import dataclass from typing import TYPE_CHECKING, NamedTuple from uuid import UUID import graphene import requests from django.conf import settings from django.core.exceptions import ValidationError from django.db import Databas...
266
8,225
saleor
saleor/graphql/product/resolvers.py
.py
from django.db.models import Exists, OuterRef, Sum from ...attribute import models as attribute_models from ...channel.models import Channel from ...order import OrderStatus from ...order.models import Order from ...permission.enums import ProductPermissions from ...permission.utils import has_one_of_permissions from ...
361
11,486
saleor
saleor/graphql/product/enums.py
.py
from typing import Final import graphene from ...product import ProductMediaTypes, ProductTypeKind from ..core.doc_category import DOC_CATEGORY_PRODUCTS from ..core.enums import to_enum from ..core.types import BaseEnum ProductTypeKindEnum: Final[graphene.Enum] = to_enum(ProductTypeKind) ProductTypeKindEnum.doc_cate...
65
1,470
saleor
saleor/graphql/product/schema.py
.py
import graphene from django.db.models import Exists, OuterRef from promise import Promise from ...core.search import prefix_search from ...permission.enums import ProductPermissions from ...permission.utils import has_one_of_permissions from ...product import models from ...product.models import ALL_PRODUCTS_PERMISSIO...
702
26,378
saleor
saleor/graphql/product/sorters.py
.py
import graphene from django.db.models import ( BooleanField, Case, Count, DateTimeField, ExpressionWrapper, F, IntegerField, Min, OuterRef, Q, QuerySet, Subquery, Value, When, ) from django.db.models.functions import Coalesce from ...product.models import ( C...
376
14,631
saleor
saleor/graphql/product/bulk_mutations/product_bulk_delete.py
.py
from collections import defaultdict import graphene from django.conf import settings from django.core.exceptions import ValidationError from django.db import transaction from django.db.models.expressions import Exists, OuterRef from ....attribute import AttributeInputType from ....attribute import models as attribute...
138
5,268
saleor
saleor/graphql/product/bulk_mutations/product_type_bulk_delete.py
.py
import graphene from django.conf import settings from django.core.exceptions import ValidationError from django.db.models import Q from django.db.models.expressions import Exists, OuterRef from ....attribute import AttributeInputType from ....attribute import models as attribute_models from ....core.tracing import tra...
81
3,196
saleor
saleor/graphql/product/bulk_mutations/product_variant_stocks_update.py
.py
from collections import defaultdict import graphene from django.core.exceptions import ValidationError from ....core.tracing import traced_atomic_transaction from ....core.utils.events import call_event from ....permission.enums import ProductPermissions from ....product import models from ....warehouse import models...
238
9,547
saleor
saleor/graphql/product/bulk_mutations/product_variant_stocks_create.py
.py
from collections import defaultdict import graphene from django.core.exceptions import ValidationError from ....core.tracing import traced_atomic_transaction from ....core.utils.events import call_event from ....permission.enums import ProductPermissions from ....warehouse.channel_stock_availability import ( trig...
168
6,570
saleor
saleor/graphql/product/bulk_mutations/__init__.py
.py
from .category_bulk_delete import CategoryBulkDelete from .collection_bulk_delete import CollectionBulkDelete from .product_bulk_create import ProductBulkCreate from .product_bulk_delete import ProductBulkDelete from .product_media_bulk_delete import ProductMediaBulkDelete from .product_type_bulk_delete import ProductT...
28
1,118
saleor
saleor/graphql/product/bulk_mutations/category_bulk_delete.py
.py
import graphene from django.conf import settings from ....permission.enums import ProductPermissions from ....product import models from ....product.utils import delete_categories from ...core.mutations import ModelBulkDeleteMutation from ...core.types import NonNullList, ProductError from ...plugins.dataloaders impor...
37
1,294
saleor
saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py
.py
from collections import defaultdict from typing import cast import graphene from django.core.exceptions import ValidationError from django.db.models import F, Subquery from django.utils import timezone from graphene.utils.str_converters import to_camel_case from ....core.tracing import traced_atomic_transaction from ...
914
34,571
saleor
saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py
.py
from collections import defaultdict from typing import cast import graphene from babel.core import get_global from django.core.exceptions import ValidationError from django.db.models import F from graphene.utils.str_converters import to_camel_case from ....attribute import AttributeType from ....core.tracing import t...
1,008
36,882
saleor
saleor/graphql/product/bulk_mutations/product_bulk_create.py
.py
import datetime from collections import defaultdict import graphene from django.core.exceptions import ValidationError from django.db import transaction from django.db.models import F from django.utils.text import slugify from graphene.utils.str_converters import to_camel_case from text_unidecode import unidecode fro...
973
37,314