Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Use orjson for JSON de-/serialization (#18585)
Patryk Zawadzki4437d19f4c10
diff --git a/pyproject.toml b/pyproject.tomlindex db1648e802..e542b47331 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -87,6 +87,7 @@ dependencies = ["python-magic-bin>=0.4.14,<0.5 ; sys_platform == 'win32'","nh3>=0.2.20","idna>=3.10",+ "orjson>=3.11.4",][project.urls]diff --git a/saleor/core/db/fields.py b/saleor/core/db/fields.pyindex fcbf1dc135..54c184d533 100644--- a/saleor/core/db/fields.py+++ b/saleor/core/db/fields.py@@ -1,8 +1,8 @@-import jsonfrom collections.abc import Callablefrom decimal import Decimalfrom functools import total_ordering+import orjsonfrom django.core import validatorsfrom django.db.models import Field, JSONFieldfrom django.db.models.expressions import Expression@@ -26,7 +26,9 @@ class SanitizedJSONField(JSONField):"""Sanitize the value for saving using the passed sanitizer."""if isinstance(value, Expression):return value- return json.dumps(self._sanitizer_method(value))+ return orjson.dumps(+ self._sanitizer_method(value), option=orjson.OPT_UTC_Z+ ).decode("utf-8")@total_orderingdiff --git a/saleor/graphql/attribute/tests/queries/test_attribute_filter.py b/saleor/graphql/attribute/tests/queries/test_attribute_filter.pyindex fe70bf140a..e6ed90a931 100644--- a/saleor/graphql/attribute/tests/queries/test_attribute_filter.py+++ b/saleor/graphql/attribute/tests/queries/test_attribute_filter.py@@ -202,9 +202,7 @@ def test_filter_attributes_in_category_invalid_category_id(# thencontent = get_graphql_content_from_response(response)- message_error = (- '{"in_category": [{"message": "Invalid ID specified.", "code": ""}]}'- )+ message_error = '{"in_category":[{"message":"Invalid ID specified.","code":""}]}'assert len(content["errors"]) == 1assert content["errors"][0]["message"] == message_errorassert content["data"]["attributes"] is None@@ -736,9 +734,7 @@ def test_filter_attributes_in_collection_invalid_category_id(# thencontent = get_graphql_content_from_response(response)- message_error = (- '{"in_collection": [{"message": "Invalid ID specified.", "code": ""}]}'- )+ message_error = '{"in_collection":[{"message":"Invalid ID specified.","code":""}]}'assert len(content["errors"]) == 1assert content["errors"][0]["message"] == message_errorassert content["data"]["attributes"] is Nonediff --git a/saleor/graphql/attribute/tests/queries/test_attribute_query.py b/saleor/graphql/attribute/tests/queries/test_attribute_query.pyindex 839d6655c7..66b861b4d3 100644--- a/saleor/graphql/attribute/tests/queries/test_attribute_query.py+++ b/saleor/graphql/attribute/tests/queries/test_attribute_query.py@@ -1014,7 +1014,7 @@ def test_attributes_query_ids_not_exists(user_api_client, category):variables = {"filter": {"ids": ["ygRqjpmXYqaTD9r=", "PBa4ZLBhnXHSz6v="]}}response = user_api_client.post_graphql(query, variables)content = get_graphql_content(response, ignore_errors=True)- message_error = '{"ids": [{"message": "Invalid ID specified.", "code": ""}]}'+ message_error = '{"ids":[{"message":"Invalid ID specified.","code":""}]}'assert len(content["errors"]) == 1assert content["errors"][0]["message"] == message_errordiff --git a/saleor/graphql/attribute/tests/queries/test_attribute_where.py b/saleor/graphql/attribute/tests/queries/test_attribute_where.pyindex 02b68e5eca..e04c27a527 100644--- a/saleor/graphql/attribute/tests/queries/test_attribute_where.py+++ b/saleor/graphql/attribute/tests/queries/test_attribute_where.py@@ -800,9 +800,7 @@ def test_attributes_filter_attributes_in_collection_invalid_collection_id(# thencontent = get_graphql_content_from_response(response)- message_error = (- '{"in_collection": [{"message": "Invalid ID specified.", "code": ""}]}'- )+ message_error = '{"in_collection":[{"message":"Invalid ID specified.","code":""}]}'assert len(content["errors"]) == 1assert content["errors"][0]["message"] == message_errorassert content["data"]["attributes"] is None@@ -1395,9 +1393,7 @@ def test_attributes_filter_in_category_invalid_category_id(# thencontent = get_graphql_content_from_response(response)- message_error = (- '{"in_category": [{"message": "Invalid ID specified.", "code": ""}]}'- )+ message_error = '{"in_category":[{"message":"Invalid ID specified.","code":""}]}'assert len(content["errors"]) == 1assert content["errors"][0]["message"] == message_errorassert content["data"]["attributes"] is Nonediff --git a/saleor/graphql/attribute/utils/shared.py b/saleor/graphql/attribute/utils/shared.pyindex cde1ef3ec7..3b0ee84e52 100644--- a/saleor/graphql/attribute/utils/shared.py+++ b/saleor/graphql/attribute/utils/shared.py@@ -1,9 +1,9 @@import datetime-import jsonfrom collections import defaultdictfrom dataclasses import dataclassfrom typing import TYPE_CHECKING, NamedTuple, cast+import orjsonfrom django.db.models import Modelfrom django.db.models.expressions import Exists, OuterRef@@ -186,7 +186,11 @@ def get_attribute_to_values_map_for_variant(if attribute.input_type == AttributeInputType.PLAIN_TEXT:attribute_values[attribute_id].append(attr_value.plain_text)elif attribute.input_type == AttributeInputType.RICH_TEXT:- attribute_values[attribute_id].append(json.dumps(attr_value.rich_text))+ attribute_values[attribute_id].append(+ orjson.dumps(attr_value.rich_text, option=orjson.OPT_UTC_Z).decode(+ "utf-8"+ )+ )elif attribute.input_type == AttributeInputType.NUMERIC:attribute_values[attribute_id].append(str(attr_value.numeric))elif attribute.input_type in [@@ -206,7 +210,10 @@ def get_values_from_pre_save_bulk_data() -> dict[int, list[str | None | datetime.datetime]]:input_type_to_field_and_action = {AttributeInputType.PLAIN_TEXT: ("plain_text", None),- AttributeInputType.RICH_TEXT: ("rich_text", json.dumps),+ AttributeInputType.RICH_TEXT: (+ "rich_text",+ lambda x: orjson.dumps(x, option=orjson.OPT_UTC_Z).decode("utf-8"),+ ),AttributeInputType.NUMERIC: ("numeric", str),AttributeInputType.DATE: ("date_time", None),AttributeInputType.DATE_TIME: ("date_time", None),diff --git a/saleor/graphql/core/connection.py b/saleor/graphql/core/connection.pyindex c72f0c4163..f5fd61802f 100644--- a/saleor/graphql/core/connection.py+++ b/saleor/graphql/core/connection.py@@ -1,9 +1,10 @@-import json+from base64 import b64encodefrom collections.abc import Callable, Iterablefrom decimal import Decimal, InvalidOperationfrom typing import TYPE_CHECKING, Anyimport graphene+import orjsonfrom django.conf import settingsfrom django.db.models import Model as DjangoModelfrom django.db.models import Q, QuerySet@@ -12,7 +13,7 @@ from graphql import GraphQLErrorfrom graphql.language.ast import FragmentSpread, InlineFragment, SelectionSetfrom graphql_relay.connection.arrayconnection import connection_from_list_slicefrom graphql_relay.connection.connectiontypes import Edge, PageInfo-from graphql_relay.utils import base64, unbase64+from graphql_relay.utils import unbase64from ...channel.exceptions import ChannelNotDefined, NoDefaultChannelfrom ..channel.utils import get_default_channel_slug_or_graphql_error@@ -38,12 +39,12 @@ def to_global_cursor(values):if not isinstance(values, Iterable):values = [values]values = [value if value is None else str(value) for value in values]- return base64(json.dumps(values))+ return b64encode(orjson.dumps(values, option=orjson.OPT_UTC_Z)).decode("utf-8")def from_global_cursor(cursor) -> list[str]:values = unbase64(cursor)- return json.loads(values)+ return orjson.loads(values)def get_field_value(instance: DjangoModel, field_name: str):@@ -517,7 +518,11 @@ def filter_qs(filterset = filterset_class(filter_input, queryset=queryset, request=request)if not filterset.is_valid():- raise GraphQLError(json.dumps(filterset.errors.get_json_data()))+ raise GraphQLError(+ orjson.dumps(+ filterset.errors.get_json_data(), option=orjson.OPT_UTC_Z+ ).decode("utf-8")+ )if isinstance(iterable, ChannelQsContext):return ChannelQsContext(filterset.qs, iterable.channel_slug)diff --git a/saleor/graphql/product/tests/queries/test_categories_query.py b/saleor/graphql/product/tests/queries/test_categories_query.pyindex 21781bc949..704597d61c 100644--- a/saleor/graphql/product/tests/queries/test_categories_query.py+++ b/saleor/graphql/product/tests/queries/test_categories_query.py@@ -59,7 +59,7 @@ def test_categories_query_ids_not_exists(user_api_client, category):variables = {"filter": {"ids": ["W3KATGDn3fq3ZH4=", "zH9pYmz7yWD3Hy8="]}}response = user_api_client.post_graphql(query, variables)content = get_graphql_content(response, ignore_errors=True)- message_error = '{"ids": [{"message": "Invalid ID specified.", "code": ""}]}'+ message_error = '{"ids":[{"message":"Invalid ID specified.","code":""}]}'assert len(content["errors"]) == 1assert content["errors"][0]["message"] == message_errorassert content["data"]["categories"] is Nonediff --git a/saleor/graphql/product/tests/queries/test_collections_query.py b/saleor/graphql/product/tests/queries/test_collections_query.pyindex 1eb09e882b..12110f6e77 100644--- a/saleor/graphql/product/tests/queries/test_collections_query.py+++ b/saleor/graphql/product/tests/queries/test_collections_query.py@@ -178,7 +178,7 @@ def test_collections_query_ids_not_exists(}response = user_api_client.post_graphql(query, variables)content = get_graphql_content(response, ignore_errors=True)- message_error = '{"ids": [{"message": "Invalid ID specified.", "code": ""}]}'+ message_error = '{"ids":[{"message":"Invalid ID specified.","code":""}]}'assert len(content["errors"]) == 1assert content["errors"][0]["message"] == message_errordiff --git a/saleor/graphql/product/tests/queries/test_product_types_query.py b/saleor/graphql/product/tests/queries/test_product_types_query.pyindex 3c10ef7242..604de5f184 100644--- a/saleor/graphql/product/tests/queries/test_product_types_query.py+++ b/saleor/graphql/product/tests/queries/test_product_types_query.py@@ -196,7 +196,7 @@ def test_product_types_query_ids_not_exists(user_api_client, category):variables = {"filter": {"ids": ["fTEJRuFHU6fd2RU=", "2XwnQNNhwCdEjhP="]}}response = user_api_client.post_graphql(query, variables)content = get_graphql_content(response, ignore_errors=True)- message_error = '{"ids": [{"message": "Invalid ID specified.", "code": ""}]}'+ message_error = '{"ids":[{"message":"Invalid ID specified.","code":""}]}'assert len(content["errors"]) == 1assert content["errors"][0]["message"] == message_errordiff --git a/saleor/graphql/views.py b/saleor/graphql/views.pyindex 601f2418e0..164e8b9677 100644--- a/saleor/graphql/views.py+++ b/saleor/graphql/views.py@@ -1,13 +1,14 @@+import decimalimport hashlibimport importlib-import jsonfrom inspect import isclassfrom typing import Any, castfrom urllib.parse import urljoin+import orjsonfrom django.conf import settingsfrom django.core.cache import cache-from django.http import HttpRequest, HttpResponseNotAllowed, JsonResponse+from django.http import HttpRequest, HttpResponse, HttpResponseNotAllowedfrom django.shortcuts import renderfrom django.views.generic import Viewfrom graphql import GraphQLBackend, GraphQLDocument, GraphQLSchema@@ -55,6 +56,29 @@ from .utils.validators import check_if_query_contains_only_schemaINT_ERROR_MSG = "Int cannot represent non 32-bit signed integer value"+def default_serializer(obj):+ if isinstance(obj, decimal.Decimal):+ return str(obj)+ raise TypeError+++class JsonResponse(HttpResponse):+ def __init__(+ self,+ data,+ safe=True,+ **kwargs,+ ):+ if safe and not isinstance(data, dict):+ raise TypeError(+ "In order to allow non-dict objects to be serialized set the "+ "safe parameter to False."+ )+ kwargs.setdefault("content_type", "application/json")+ data = orjson.dumps(data, option=orjson.OPT_UTC_Z, default=default_serializer)+ super().__init__(content=data, **kwargs)++class GraphQLView(View):# This class is our implementation of `graphene_django.views.GraphQLView`,# which was extended to support the following features:@@ -462,8 +486,8 @@ class GraphQLView(View):if content_type == "application/graphql":return {"query": request.body.decode("utf-8")}if content_type == "application/json":- body = request.body.decode("utf-8")- return json.loads(body)+ body = request.body+ return orjson.loads(body)if content_type in ["application/x-www-form-urlencoded", "multipart/form-data"]:return request.POSTreturn {}@@ -477,8 +501,8 @@ class GraphQLView(View):operation_name = Noneif request.content_type == "multipart/form-data":- operations = json.loads(data.get("operations", "{}"))- files_map = json.loads(data.get("map", "{}"))+ operations = orjson.loads(data.get("operations", "{}"))+ files_map = orjson.loads(data.get("map", "{}"))for file_key in files_map:# file key is which file it is in the form-datafile_instances = files_map[file_key]diff --git a/uv.lock b/uv.lockindex ba40eaf02b..a72fc24ea9 100644--- a/uv.lock+++ b/uv.lock@@ -1716,6 +1716,29 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/27/6b/a8fb94760ef8da5ec283e488eb43235eac3ae7514385a51b6accf881e671/opentelemetry_semantic_conventions-0.53b1-py3-none-any.whl", hash = "sha256:21df3ed13f035f8f3ea42d07cbebae37020367a53b47f1ebee3b10a381a00208", size = 188443, upload-time = "2025-04-15T16:02:10.095Z" },]+[[package]]+name = "orjson"+version = "3.11.7"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/53/45/b268004f745ede84e5798b48ee12b05129d19235d0e15267aa57dcdb400b/orjson-3.11.7.tar.gz", hash = "sha256:9b1a67243945819ce55d24a30b59d6a168e86220452d2c96f4d1f093e71c0c49", size = 6144992, upload-time = "2026-02-02T15:38:49.29Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/80/bf/76f4f1665f6983385938f0e2a5d7efa12a58171b8456c252f3bae8a4cf75/orjson-3.11.7-cp312-cp312-macosx_10_15_x86_64.macosx_11_0_arm64.macosx_10_15_universal2.whl", hash = "sha256:bd03ea7606833655048dab1a00734a2875e3e86c276e1d772b2a02556f0d895f", size = 228545, upload-time = "2026-02-02T15:37:46.376Z" },+ { url = "https://files.pythonhosted.org/packages/79/53/6c72c002cb13b5a978a068add59b25a8bdf2800ac1c9c8ecdb26d6d97064/orjson-3.11.7-cp312-cp312-macosx_15_0_arm64.whl", hash = "sha256:89e440ebc74ce8ab5c7bc4ce6757b4a6b1041becb127df818f6997b5c71aa60b", size = 125224, upload-time = "2026-02-02T15:37:47.697Z" },+ { url = "https://files.pythonhosted.org/packages/2c/83/10e48852865e5dd151bdfe652c06f7da484578ed02c5fca938e3632cb0b8/orjson-3.11.7-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5ede977b5fe5ac91b1dffc0a517ca4542d2ec8a6a4ff7b2652d94f640796342a", size = 128154, upload-time = "2026-02-02T15:37:48.954Z" },+ { url = "https://files.pythonhosted.org/packages/6e/52/a66e22a2b9abaa374b4a081d410edab6d1e30024707b87eab7c734afe28d/orjson-3.11.7-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:b7b1dae39230a393df353827c855a5f176271c23434cfd2db74e0e424e693e10", size = 123548, upload-time = "2026-02-02T15:37:50.187Z" },+ { url = "https://files.pythonhosted.org/packages/de/38/605d371417021359f4910c496f764c48ceb8997605f8c25bf1dfe58c0ebe/orjson-3.11.7-cp312-cp312-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ed46f17096e28fb28d2975834836a639af7278aa87c84f68ab08fbe5b8bd75fa", size = 129000, upload-time = "2026-02-02T15:37:51.426Z" },+ { url = "https://files.pythonhosted.org/packages/44/98/af32e842b0ffd2335c89714d48ca4e3917b42f5d6ee5537832e069a4b3ac/orjson-3.11.7-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3726be79e36e526e3d9c1aceaadbfb4a04ee80a72ab47b3f3c17fefb9812e7b8", size = 141686, upload-time = "2026-02-02T15:37:52.607Z" },+ { url = "https://files.pythonhosted.org/packages/96/0b/fc793858dfa54be6feee940c1463370ece34b3c39c1ca0aa3845f5ba9892/orjson-3.11.7-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:0724e265bc548af1dedebd9cb3d24b4e1c1e685a343be43e87ba922a5c5fff2f", size = 130812, upload-time = "2026-02-02T15:37:53.944Z" },+ { url = "https://files.pythonhosted.org/packages/dc/91/98a52415059db3f374757d0b7f0f16e3b5cd5976c90d1c2b56acaea039e6/orjson-3.11.7-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e7745312efa9e11c17fbd3cb3097262d079da26930ae9ae7ba28fb738367cbad", size = 133440, upload-time = "2026-02-02T15:37:55.615Z" },+ { url = "https://files.pythonhosted.org/packages/dc/b6/cb540117bda61791f46381f8c26c8f93e802892830a6055748d3bb1925ab/orjson-3.11.7-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:f904c24bdeabd4298f7a977ef14ca2a022ca921ed670b92ecd16ab6f3d01f867", size = 138386, upload-time = "2026-02-02T15:37:56.814Z" },+ { url = "https://files.pythonhosted.org/packages/63/1a/50a3201c334a7f17c231eee5f841342190723794e3b06293f26e7cf87d31/orjson-3.11.7-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:b9fc4d0f81f394689e0814617aadc4f2ea0e8025f38c226cbf22d3b5ddbf025d", size = 408853, upload-time = "2026-02-02T15:37:58.291Z" },+ { url = "https://files.pythonhosted.org/packages/87/cd/8de1c67d0be44fdc22701e5989c0d015a2adf391498ad42c4dc589cd3013/orjson-3.11.7-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:849e38203e5be40b776ed2718e587faf204d184fc9a008ae441f9442320c0cab", size = 144130, upload-time = "2026-02-02T15:38:00.163Z" },+ { url = "https://files.pythonhosted.org/packages/0f/fe/d605d700c35dd55f51710d159fc54516a280923cd1b7e47508982fbb387d/orjson-3.11.7-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:4682d1db3bcebd2b64757e0ddf9e87ae5f00d29d16c5cdf3a62f561d08cc3dd2", size = 134818, upload-time = "2026-02-02T15:38:01.507Z" },+ { url = "https://files.pythonhosted.org/packages/e4/e4/15ecc67edb3ddb3e2f46ae04475f2d294e8b60c1825fbe28a428b93b3fbd/orjson-3.11.7-cp312-cp312-win32.whl", hash = "sha256:f4f7c956b5215d949a1f65334cf9d7612dde38f20a95f2315deef167def91a6f", size = 127923, upload-time = "2026-02-02T15:38:02.75Z" },+ { url = "https://files.pythonhosted.org/packages/34/70/2e0855361f76198a3965273048c8e50a9695d88cd75811a5b46444895845/orjson-3.11.7-cp312-cp312-win_amd64.whl", hash = "sha256:bf742e149121dc5648ba0a08ea0871e87b660467ef168a3a5e53bc1fbd64bb74", size = 125007, upload-time = "2026-02-02T15:38:04.032Z" },+ { url = "https://files.pythonhosted.org/packages/68/40/c2051bd19fc467610fed469dc29e43ac65891571138f476834ca192bc290/orjson-3.11.7-cp312-cp312-win_arm64.whl", hash = "sha256:26c3b9132f783b7d7903bf1efb095fed8d4a3a85ec0d334ee8beff3d7a4749d5", size = 126089, upload-time = "2026-02-02T15:38:05.297Z" },+]+[[package]]name = "packaging"version = "25.0"@@ -2593,6 +2616,7 @@ dependencies = [{ name = "opentelemetry-distro", extra = ["otlp"], marker = "platform_python_implementation != 'PyPy'" },{ name = "opentelemetry-sdk", marker = "platform_python_implementation != 'PyPy'" },{ name = "opentelemetry-semantic-conventions", marker = "platform_python_implementation != 'PyPy'" },+ { name = "orjson", marker = "platform_python_implementation != 'PyPy'" },{ name = "petl", marker = "platform_python_implementation != 'PyPy'" },{ name = "phonenumberslite", marker = "platform_python_implementation != 'PyPy'" },{ name = "pillow", marker = "platform_python_implementation != 'PyPy'" },@@ -2709,6 +2733,7 @@ requires-dist = [{ name = "opentelemetry-distro", extras = ["otlp"], specifier = ">=0.53b1,<0.54" },{ name = "opentelemetry-sdk", specifier = ">=1.32.1,<2" },{ name = "opentelemetry-semantic-conventions", specifier = ">=0.53b1,<0.54" },+ { name = "orjson", specifier = ">=3.11.4" },{ name = "petl", specifier = "==1.7.17" },{ name = "phonenumberslite", specifier = ">=9.0.7,<10" },{ name = "pillow", specifier = ">=11.1.0,<12" },