Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Remove remaining traces of WSGI (#17297)

Patryk Zawadzki4ee7326d6b1e
diff --git a/saleor/payment/gateways/adyen/plugin.py b/saleor/payment/gateways/adyen/plugin.py
index 02f7914430..2204c48940 100644
--- a/saleor/payment/gateways/adyen/plugin.py
+++ b/saleor/payment/gateways/adyen/plugin.py
@@ -6,7 +6,6 @@ import opentracing
import opentracing.tags
from django.contrib.auth.hashers import make_password
from django.core.exceptions import ObjectDoesNotExist, ValidationError
-from django.core.handlers.wsgi import WSGIRequest
from django.http import HttpResponse, HttpResponseNotFound
from django.urls import reverse
from requests.exceptions import SSLError
@@ -14,6 +13,7 @@ from requests.exceptions import SSLError
from ....checkout.fetch import CheckoutInfo, CheckoutLineInfo
from ....core.utils import build_absolute_uri
from ....core.utils.url import prepare_url
+from ....graphql.core import SaleorContext
from ....order.events import external_notification_event
from ....plugins.base_plugin import BasePlugin, ConfigurationTypeField
from ....plugins.error_codes import PluginErrorCode
@@ -240,7 +240,9 @@ class AdyenGatewayPlugin(BasePlugin):
base_url = build_absolute_uri(api_path)
return urljoin(base_url, "webhooks")
- def webhook(self, request: WSGIRequest, path: str, previous_value) -> HttpResponse:
+ def webhook(
+ self, request: SaleorContext, path: str, previous_value
+ ) -> HttpResponse:
"""Handle a request received from Adyen.
The method handles two types of requests:
diff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.py
index 851c7e51ea..642a4f7887 100644
--- a/saleor/payment/gateways/adyen/webhooks.py
+++ b/saleor/payment/gateways/adyen/webhooks.py
@@ -14,7 +14,6 @@ import Adyen
import graphene
from django.contrib.auth.hashers import check_password
from django.core.exceptions import ValidationError
-from django.core.handlers.wsgi import WSGIRequest
from django.forms.models import model_to_dict
from django.http import (
HttpResponse,
@@ -33,6 +32,7 @@ from ....checkout.models import Checkout
from ....core.prices import quantize_price
from ....core.transactions import transaction_with_commit_on_errors
from ....core.utils.url import prepare_url
+from ....graphql.core import SaleorContext
from ....graphql.core.utils import from_global_id_or_error
from ....order.actions import (
cancel_order,
@@ -984,7 +984,7 @@ def validate_merchant_account(
@transaction_with_commit_on_errors()
-def handle_webhook(request: WSGIRequest, gateway_config: "GatewayConfig"):
+def handle_webhook(request: SaleorContext, gateway_config: "GatewayConfig"):
try:
json_data = json.loads(request.body)
except JSONDecodeError:
@@ -1020,7 +1020,7 @@ class HttpResponseRedirectWithTrustedProtocol(HttpResponseRedirect):
@transaction_with_commit_on_errors()
def handle_additional_actions(
- request: WSGIRequest, payment_details: Callable, channel_slug: str
+ request: SaleorContext, payment_details: Callable, channel_slug: str
):
"""Handle redirect with additional actions.
@@ -1089,7 +1089,7 @@ def handle_additional_actions(
return HttpResponseRedirectWithTrustedProtocol(redirect_url)
-def prepare_api_request_data(request: WSGIRequest, data: dict):
+def prepare_api_request_data(request: SaleorContext, data: dict):
if "parameters" not in data or "payment_data" not in data:
raise KeyError(
"Cannot perform payment. Lack of payment data and parameters information."
diff --git a/saleor/payment/gateways/stripe/plugin.py b/saleor/payment/gateways/stripe/plugin.py
index ee705a908b..d8ede7e08e 100644
--- a/saleor/payment/gateways/stripe/plugin.py
+++ b/saleor/payment/gateways/stripe/plugin.py
@@ -2,11 +2,11 @@ import logging
from typing import TYPE_CHECKING
from django.core.exceptions import ValidationError
-from django.core.handlers.wsgi import WSGIRequest
from django.http import HttpResponse, HttpResponseNotFound
from django.http.request import split_domain_port
from ....core.utils import get_domain
+from ....graphql.core import SaleorContext
from ....graphql.core.enums import PluginErrorCode
from ....plugins.base_plugin import BasePlugin, ConfigurationTypeField
from ... import PaymentError, TransactionKind
@@ -126,7 +126,9 @@ class StripeGatewayPlugin(BasePlugin):
store_customer=True,
)
- def webhook(self, request: WSGIRequest, path: str, previous_value) -> HttpResponse:
+ def webhook(
+ self, request: SaleorContext, path: str, previous_value
+ ) -> HttpResponse:
config = self.config
if not self.channel:
return HttpResponseNotFound()
diff --git a/saleor/payment/gateways/stripe/webhooks.py b/saleor/payment/gateways/stripe/webhooks.py
index 78346f6184..98b3212df6 100644
--- a/saleor/payment/gateways/stripe/webhooks.py
+++ b/saleor/payment/gateways/stripe/webhooks.py
@@ -3,7 +3,6 @@ from typing import cast
import stripe
from django.core.exceptions import ValidationError
-from django.core.handlers.wsgi import WSGIRequest
from django.db.models import Prefetch
from django.http import HttpResponse
from stripe.error import SignatureVerificationError
@@ -14,6 +13,7 @@ from ....checkout.complete_checkout import complete_checkout
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ....checkout.models import Checkout
from ....core.transactions import transaction_with_commit_on_errors
+from ....graphql.core import SaleorContext
from ....order.actions import order_charged, order_refunded, order_voided
from ....order.fetch import fetch_order_info
from ....order.models import Order
@@ -49,7 +49,7 @@ logger = logging.getLogger(__name__)
@transaction_with_commit_on_errors()
def handle_webhook(
- request: WSGIRequest, gateway_config: "GatewayConfig", channel_slug: str
+ request: SaleorContext, gateway_config: "GatewayConfig", channel_slug: str
):
payload = request.body
sig_header = request.headers["stripe-signature"]
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 1ed0a969ad..9fa1a3502c 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -5,13 +5,13 @@ from dataclasses import dataclass
from decimal import Decimal
from typing import TYPE_CHECKING, Any, Optional, Union
-from django.core.handlers.wsgi import WSGIRequest
from django.http import HttpResponse
from django.utils.functional import SimpleLazyObject
from prices import TaxedMoney
from promise.promise import Promise
from ..core.models import EventDelivery
+from ..graphql.core import SaleorContext
from ..payment.interface import (
CustomerSource,
GatewayResponse,
@@ -336,7 +336,7 @@ class BasePlugin:
# Authenticate user which should be assigned to the request.
#
# Overwrite this method if the plugin handles authentication flow.
- authenticate_user: Callable[[WSGIRequest, Optional["User"]], Union["User", None]]
+ authenticate_user: Callable[[SaleorContext, Optional["User"]], Union["User", None]]
authorize_payment: Callable[["PaymentData", Any], GatewayResponse]
@@ -635,18 +635,18 @@ class BasePlugin:
# Handle authentication request.
#
# Overwrite this method if the plugin handles authentication flow.
- external_authentication_url: Callable[[dict, WSGIRequest, dict], dict]
+ external_authentication_url: Callable[[dict, SaleorContext, dict], dict]
# Handle logout request.
#
# Overwrite this method if the plugin handles logout flow.
- external_logout: Callable[[dict, WSGIRequest, dict], Any]
+ external_logout: Callable[[dict, SaleorContext, dict], Any]
# Handle authentication request responsible for obtaining access tokens.
#
# Overwrite this method if the plugin handles authentication flow.
external_obtain_access_tokens: Callable[
- [dict, WSGIRequest, ExternalAccessTokens], ExternalAccessTokens
+ [dict, SaleorContext, ExternalAccessTokens], ExternalAccessTokens
]
# Handle authentication refresh request.
@@ -654,14 +654,14 @@ class BasePlugin:
# Overwrite this method if the plugin handles authentication flow and supports
# refreshing the access.
external_refresh: Callable[
- [dict, WSGIRequest, ExternalAccessTokens], ExternalAccessTokens
+ [dict, SaleorContext, ExternalAccessTokens], ExternalAccessTokens
]
# Verify the provided authentication data.
#
# Overwrite this method if the plugin should validate the authentication data.
external_verify: Callable[
- [dict, WSGIRequest, tuple[Union["User", None], dict]],
+ [dict, SaleorContext, tuple[Union["User", None], dict]],
tuple[Union["User", None], dict],
]
@@ -1700,7 +1700,7 @@ class BasePlugin:
# Handle received http request.
#
# Overwrite this method if the plugin expects the incoming requests.
- webhook: Callable[[WSGIRequest, str, Any], HttpResponse]
+ webhook: Callable[[SaleorContext, str, Any], HttpResponse]
# Triggers retry mechanism for event delivery
#
diff --git a/saleor/plugins/openid_connect/plugin.py b/saleor/plugins/openid_connect/plugin.py
index c1205d9834..05943acec9 100644
--- a/saleor/plugins/openid_connect/plugin.py
+++ b/saleor/plugins/openid_connect/plugin.py
@@ -4,7 +4,6 @@ from typing import cast
from authlib.common.errors import AuthlibBaseError
from django.core import signing
from django.core.exceptions import ValidationError
-from django.core.handlers.wsgi import WSGIRequest
from jwt import DecodeError, ExpiredSignatureError, InvalidTokenError
from requests import HTTPError, PreparedRequest
@@ -18,6 +17,7 @@ from ...core.jwt import (
get_user_from_payload,
jwt_decode,
)
+from ...graphql.core import SaleorContext
from ...permission.enums import get_permissions_codename, get_permissions_from_names
from ..base_plugin import BasePlugin, ConfigurationTypeField, ExternalAccessTokens
from ..error_codes import PluginErrorCode
@@ -242,7 +242,7 @@ class OpenIDConnectPlugin(BasePlugin):
return user_permissions
def external_obtain_access_tokens(
- self, data: dict, request: WSGIRequest, previous_value
+ self, data: dict, request: SaleorContext, previous_value
) -> ExternalAccessTokens:
if not self.active:
return previous_value
@@ -341,7 +341,7 @@ class OpenIDConnectPlugin(BasePlugin):
return email_domain in staff_user_domains
def external_authentication_url(
- self, data: dict, request: WSGIRequest, previous_value
+ self, data: dict, request: SaleorContext, previous_value
) -> dict:
if not self.active:
return previous_value
@@ -371,7 +371,7 @@ class OpenIDConnectPlugin(BasePlugin):
return {"authorizationUrl": uri}
def external_refresh(
- self, data: dict, request: WSGIRequest, previous_value
+ self, data: dict, request: SaleorContext, previous_value
) -> ExternalAccessTokens:
if not self.active:
return previous_value
@@ -445,7 +445,7 @@ class OpenIDConnectPlugin(BasePlugin):
)
return user_permissions
- def external_logout(self, data: dict, request: WSGIRequest, previous_value):
+ def external_logout(self, data: dict, request: SaleorContext, previous_value):
if not self.active:
return previous_value
@@ -461,7 +461,7 @@ class OpenIDConnectPlugin(BasePlugin):
return {"logoutUrl": req.url}
def external_verify(
- self, data: dict, request: WSGIRequest, previous_value
+ self, data: dict, request: SaleorContext, previous_value
) -> tuple[User | None, dict]:
if not self.active:
return previous_value
@@ -492,7 +492,7 @@ class OpenIDConnectPlugin(BasePlugin):
)
return user, payload
- def authenticate_user(self, request: WSGIRequest, previous_value) -> User | None:
+ def authenticate_user(self, request: SaleorContext, previous_value) -> User | None:
if not self.active:
return previous_value
token = get_token_from_request(request)
diff --git a/saleor/plugins/tests/sample_plugins.py b/saleor/plugins/tests/sample_plugins.py
index b29d3e889d..472555adcb 100644
--- a/saleor/plugins/tests/sample_plugins.py
+++ b/saleor/plugins/tests/sample_plugins.py
@@ -2,12 +2,12 @@ from collections import defaultdict
from decimal import Decimal
from typing import TYPE_CHECKING, Any, Optional, Union
-from django.core.handlers.wsgi import WSGIRequest
from django.http import HttpResponse, HttpResponseNotFound, JsonResponse
from prices import Money, TaxedMoney
from ...account.models import User
from ...core.taxes import TaxData, TaxLineData, TaxType
+from ...graphql.core import SaleorContext
from ...order.interface import OrderTaxedPricesData
from ...payment.interface import (
PaymentGatewayData,
@@ -90,7 +90,9 @@ class PluginSample(BasePlugin):
},
}
- def webhook(self, request: WSGIRequest, path: str, previous_value) -> HttpResponse:
+ def webhook(
+ self, request: SaleorContext, path: str, previous_value
+ ) -> HttpResponse:
if path == "/webhook/paid":
return JsonResponse(data={"received": True, "paid": True})
if path == "/webhook/failed":
@@ -170,36 +172,38 @@ class PluginSample(BasePlugin):
return [TaxType(code="123", description="abc")]
def external_authentication_url(
- self, data: dict, request: WSGIRequest, previous_value
+ self, data: dict, request: SaleorContext, previous_value
) -> dict:
return {"authorizeUrl": "http://www.auth.provider.com/authorize/"}
def external_obtain_access_tokens(
- self, data: dict, request: WSGIRequest, previous_value
+ self, data: dict, request: SaleorContext, previous_value
) -> ExternalAccessTokens:
return ExternalAccessTokens(
token="token1", refresh_token="refresh2", csrf_token="csrf3"
)
def external_refresh(
- self, data: dict, request: WSGIRequest, previous_value
+ self, data: dict, request: SaleorContext, previous_value
) -> ExternalAccessTokens:
return ExternalAccessTokens(
token="token4", refresh_token="refresh5", csrf_token="csrf6"
)
def external_verify(
- self, data: dict, request: WSGIRequest, previous_value
+ self, data: dict, request: SaleorContext, previous_value
) -> tuple[User | None, dict]:
user = User.objects.get()
return user, {"some_data": "data"}
def authenticate_user(
- self, request: WSGIRequest, previous_value
+ self, request: SaleorContext, previous_value
) -> Optional["User"]:
return User.objects.filter().first()
- def external_logout(self, data: dict, request: WSGIRequest, previous_value) -> dict:
+ def external_logout(
+ self, data: dict, request: SaleorContext, previous_value
+ ) -> dict:
return {"logoutUrl": "http://www.auth.provider.com/logout/"}
def sale_created(
@@ -403,7 +407,7 @@ class PluginInactive(BasePlugin):
DEFAULT_ACTIVE = False
def external_obtain_access_tokens(
- self, data: dict, request: WSGIRequest, previous_value
+ self, data: dict, request: SaleorContext, previous_value
) -> ExternalAccessTokens:
return ExternalAccessTokens(
token="token1", refresh_token="refresh2", csrf_token="csrf3"
diff --git a/saleor/settings.py b/saleor/settings.py
index fb36969abe..c8d739670f 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -66,8 +66,6 @@ PROJECT_ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), ".."))
ROOT_URLCONF = "saleor.urls"
-WSGI_APPLICATION = "saleor.wsgi.application"
-
ADMINS = (
# ('Your Name', '[email protected]'),
)
diff --git a/saleor/wsgi/__init__.py b/saleor/wsgi/__init__.py
deleted file mode 100644
index 9bdba7097b..0000000000
--- a/saleor/wsgi/__init__.py
+++ /dev/null
@@ -1,46 +0,0 @@
-"""WSGI config for Saleor project.
-
-This module contains the WSGI application used by Django's development server
-and any production WSGI deployments. It should expose a module-level variable
-named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
-this application via the ``WSGI_APPLICATION`` setting.
-
-Usually you will have the standard Django WSGI application here, but it also
-might make sense to replace the whole Django WSGI application with a custom one
-that later delegates to the Django one. For example, you could introduce WSGI
-middleware here, or combine a Django application with an application of another
-framework.
-"""
-
-import os
-
-from django.core.wsgi import get_wsgi_application
-from django.utils.functional import SimpleLazyObject
-
-from saleor.wsgi.health_check import health_check
-
-
-def get_allowed_host_lazy():
- from django.conf import settings
-
- return settings.ALLOWED_HOSTS[0]
-
-
-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "saleor.settings")
-
-application = get_wsgi_application()
-application = health_check(application, "/health/")
-
-# Warm-up the django application instead of letting it lazy-load
-application(
- {
- "REQUEST_METHOD": "GET",
- "SERVER_NAME": SimpleLazyObject(get_allowed_host_lazy),
- "REMOTE_ADDR": "127.0.0.1",
- "SERVER_PORT": 80,
- "PATH_INFO": "/graphql/",
- "wsgi.input": b"",
- "wsgi.multiprocess": True,
- },
- lambda x, y: None,
-)
diff --git a/saleor/wsgi/health_check.py b/saleor/wsgi/health_check.py
deleted file mode 100644
index e829b6bac2..0000000000
--- a/saleor/wsgi/health_check.py
+++ /dev/null
@@ -1,8 +0,0 @@
-def health_check(application, health_url):
- def health_check_wrapper(environ, start_response):
- if environ.get("PATH_INFO") == health_url:
- start_response("200 OK", [("Content-Type", "text/plain")])
- return []
- return application(environ, start_response)
-
- return health_check_wrapper
diff --git a/saleor/wsgi/uwsgi.ini b/saleor/wsgi/uwsgi.ini
deleted file mode 100644
index 36f5b3a641..0000000000
--- a/saleor/wsgi/uwsgi.ini
+++ /dev/null
@@ -1,15 +0,0 @@
-[uwsgi]
-die-on-term = true
-enable-threads = true
-http = :$(PORT)
-log-format = UWSGI uwsgi "%(method) %(uri) %(proto)" %(status) %(size) %(msecs)ms [PID:%(pid):Worker-%(wid)] [RSS:%(rssM)MB]
-master = true
-max-requests = 100
-memory-report = true
-module = saleor.wsgi:application
-processes = 4
-static-map = /static=/app/static
-mimefile = /etc/mime.types
-ignore-sigpipe = true
-ignore-write-errors = true
-disable-write-exception=true