Skip to content

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

Add saleor.demo module for entire demo configuration

Marcin Gębala7080ee0f51da
diff --git a/saleor/core/management/commands/cleardb.py b/saleor/core/management/commands/cleardb.py
index 30d9ee1cd8..0122aaf2af 100644
--- a/saleor/core/management/commands/cleardb.py
+++ b/saleor/core/management/commands/cleardb.py
@@ -1,8 +1,9 @@
"""Clear random data.
This command removes random data generated by `populatedb` command, such as example
-orders, products or customer accounts. It doesn't remove shop's configuration, such as
-an admin account, site settings or menus.
+orders, products or customer accounts. It doesn't remove shop's configuration, such as:
+staff accounts, service accounts, plugin configurations, site settings or navigation
+menus.
"""
from __future__ import unicode_literals
@@ -11,13 +12,17 @@ from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q
-from saleor.account.models import User
-from saleor.checkout.models import Checkout
-from saleor.discount.models import Sale, Voucher
-from saleor.order.models import Order
-from saleor.payment.models import Payment, Transaction
-from saleor.product.models import Product
-from saleor.shipping.models import ShippingMethod
+from ....account.models import User
+from ....checkout.models import Checkout
+from ....discount.models import Sale, Voucher
+from ....giftcard.models import GiftCard
+from ....order.models import Order
+from ....page.models import Page
+from ....payment.models import Payment, Transaction
+from ....product.models import Attribute, Category, Collection, Product, ProductType
+from ....shipping.models import ShippingMethod, ShippingZone
+from ....warehouse.models import Warehouse
+from ....webhook.models import Webhook
class Command(BaseCommand):
@@ -49,15 +54,42 @@ class Command(BaseCommand):
Product.objects.all().delete()
self.stdout.write("Removed products")
+ ProductType.objects.all().delete()
+ self.stdout.write("Removed product types")
+
+ Attribute.objects.all().delete()
+ self.stdout.write("Removed attributes")
+
+ Category.objects.all().delete()
+ self.stdout.write("Removed categories")
+
+ Collection.objects.all().delete()
+ self.stdout.write("Removed collections")
+
Sale.objects.all().delete()
self.stdout.write("Removed sales")
ShippingMethod.objects.all().delete()
self.stdout.write("Removed shipping methods")
+ ShippingZone.objects.all().delete()
+ self.stdout.write("Removed shipping zones")
+
Voucher.objects.all().delete()
self.stdout.write("Removed vouchers")
+ GiftCard.objects.all().delete()
+ self.stdout.write("Removed gift cards")
+
+ self.stdout.write("Removed warehouses")
+ Warehouse.objects.all().delete()
+
+ Page.objects.all().delete()
+ self.stdout.write("Removed pages")
+
+ Webhook.objects.all().delete()
+ self.stdout.write("Removed webhooks")
+
# Delete all users except for staff members.
staff = User.objects.filter(Q(is_staff=True) | Q(is_superuser=True))
User.objects.exclude(pk__in=staff).delete()
diff --git a/saleor/core/management/commands/populatedb.py b/saleor/core/management/commands/populatedb.py
index 722f631ecd..73bd838333 100644
--- a/saleor/core/management/commands/populatedb.py
+++ b/saleor/core/management/commands/populatedb.py
@@ -6,10 +6,8 @@ from django.core.management.base import BaseCommand
from django.db import connection
from ....account.utils import create_superuser
-from ....core.utils import is_demo_mode
from ...utils.random_data import (
add_address_to_admin,
- configure_braintree,
create_gift_card,
create_menus,
create_orders,
@@ -122,10 +120,3 @@ class Command(BaseCommand):
for msg in create_permission_groups():
self.stdout.write(msg)
-
- if is_demo_mode():
- is_configured = configure_braintree()
- if is_configured:
- self.stdout.write("Configured Braintree")
- else:
- self.stdout.write("Failed to configure Braintree")
diff --git a/saleor/core/utils/__init__.py b/saleor/core/utils/__init__.py
index 4bfa76d555..7123a3490d 100644
--- a/saleor/core/utils/__init__.py
+++ b/saleor/core/utils/__init__.py
@@ -156,8 +156,3 @@ def generate_unique_slug(
unique_slug = f"{slug}-{extension}"
return unique_slug
-
-
-def is_demo_mode():
- """Return True if Saleor is running in the "demo" mode."""
- return getattr(settings, "DEMO", False)
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index 8864e7f019..d2d75b45f7 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -43,7 +43,6 @@ from ...order.models import Fulfillment, Order, OrderLine
from ...order.utils import update_order_status
from ...page.models import Page
from ...payment import gateway
-from ...payment.gateways.braintree.plugin import BraintreeGatewayPlugin
from ...payment.utils import create_payment
from ...product.models import (
AssignedProductAttribute,
@@ -1195,28 +1194,3 @@ def get_product_list_images_dir(placeholder_dir):
def get_image(image_dir, image_name):
img_path = os.path.join(image_dir, image_name)
return File(open(img_path, "rb"), name=image_name)
-
-
-def configure_braintree():
- braintree_api_key = getattr(settings, "BRAINTREE_API_KEY", "")
- braintree_merchant_id = getattr(settings, "BRAINTREE_MERCHANT_ID", "")
- braintree_secret = getattr(settings, "BRAINTREE_SECRET_API_KEY", "")
-
- if not (braintree_api_key and braintree_merchant_id and braintree_secret):
- return False
-
- manager = get_extensions_manager()
- manager.get_plugin_configuration(BraintreeGatewayPlugin.PLUGIN_NAME)
- manager.save_plugin_configuration(
- BraintreeGatewayPlugin.PLUGIN_NAME,
- {
- "active": True,
- "configuration": [
- {"name": "Public API key", "value": braintree_api_key},
- {"name": "Merchant ID", "value": braintree_merchant_id},
- {"name": "Secret API key", "value": braintree_secret},
- {"name": "Use sandbox", "value": True},
- ],
- },
- )
- return True
diff --git a/saleor/demo/__init__.py b/saleor/demo/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/demo/management/__init__.py b/saleor/demo/management/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/demo/management/commands/__init__.py b/saleor/demo/management/commands/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/demo/management/commands/populatedb.py b/saleor/demo/management/commands/populatedb.py
new file mode 100644
index 0000000000..7b69283fbe
--- /dev/null
+++ b/saleor/demo/management/commands/populatedb.py
@@ -0,0 +1,43 @@
+from django.conf import settings
+
+from ....core.management.commands.populatedb import Command as PopulateDBCommand
+from ....extensions.manager import get_extensions_manager
+from ....payment.gateways.braintree.plugin import BraintreeGatewayPlugin
+
+
+def configure_braintree():
+ braintree_api_key = getattr(settings, "BRAINTREE_API_KEY", "")
+ braintree_merchant_id = getattr(settings, "BRAINTREE_MERCHANT_ID", "")
+ braintree_secret = getattr(settings, "BRAINTREE_SECRET_API_KEY", "")
+
+ if not (braintree_api_key and braintree_merchant_id and braintree_secret):
+ return False
+
+ manager = get_extensions_manager()
+ manager.get_plugin_configuration(BraintreeGatewayPlugin.PLUGIN_NAME)
+ manager.save_plugin_configuration(
+ BraintreeGatewayPlugin.PLUGIN_NAME,
+ {
+ "active": True,
+ "configuration": [
+ {"name": "Public API key", "value": braintree_api_key},
+ {"name": "Merchant ID", "value": braintree_merchant_id},
+ {"name": "Secret API key", "value": braintree_secret},
+ {"name": "Use sandbox", "value": True},
+ ],
+ },
+ )
+ return True
+
+
+class Command(PopulateDBCommand):
+ def handle(self, *args, **options):
+ super().handle(args, options)
+ is_configured = configure_braintree()
+ if is_configured:
+ self.stdout.write("Configured Braintree")
+ else:
+ self.stdout.write(
+ "Failed to configure Braintree. Check if proper environment variables "
+ "are set."
+ )
diff --git a/saleor/settings_demo.py b/saleor/demo/settings.py
similarity index 82%
rename from saleor/settings_demo.py
rename to saleor/demo/settings.py
index c2d27c4a56..d94fca1856 100644
--- a/saleor/settings_demo.py
+++ b/saleor/demo/settings.py
@@ -14,16 +14,17 @@ for more details)
import logging
import re
-from .settings import * # noqa: F403, lgtm [py/polluting-import]
+from ..settings import * # noqa: F403, lgtm [py/polluting-import]
logger = logging.getLogger(__name__)
-# DEMO-specific settings
-
-DEMO = True
+# Override urls to use different GraphQL view on demo
+ROOT_URLCONF = "saleor.demo.urls"
PLUGINS += ["saleor.extensions.plugins.anonymize.plugin.AnonymizePlugin"]
+MIDDLEWARE += ["saleor.core.middleware.ReadOnlyMiddleware"]
+
BRAINTREE_API_KEY = os.environ.get("BRAINTREE_API_KEY")
BRAINTREE_MERCHANT_ID = os.environ.get("BRAINTREE_MERCHANT_ID")
BRAINTREE_SECRET_API_KEY = os.environ.get("BRAINTREE_SECRET_API_KEY")
@@ -41,6 +42,12 @@ PWA_DASHBOARD_URL_RE = re.compile("^https?://[^/]+/dashboard/.*")
ROOT_EMAIL = os.environ.get("ROOT_EMAIL")
+# Remove "saleor.core" and add it after adding "saleor.demo", to have "populatedb"
+# command overriden when using demo settings
+# (see saleor.demo.management.commands.populatedb).
+INSTALLED_APPS.remove("saleor.core")
+INSTALLED_APPS += ["saleor.demo", "saleor.core"]
+
def _get_project_name_from_url(url: str) -> str:
if PWA_DASHBOARD_URL_RE.match(url):
diff --git a/saleor/demo/urls.py b/saleor/demo/urls.py
new file mode 100644
index 0000000000..84f99fa26e
--- /dev/null
+++ b/saleor/demo/urls.py
@@ -0,0 +1,12 @@
+from django.urls import path
+from django.views.decorators.csrf import csrf_exempt
+
+from ..graphql.api import schema
+from ..urls import urlpatterns as core_urlpatterns
+from .views import DemoGraphQLView
+
+urlpatterns = [
+ path("graphql/", csrf_exempt(DemoGraphQLView.as_view(schema=schema)), name="api"),
+]
+
+urlpatterns += core_urlpatterns
diff --git a/saleor/demo/views.py b/saleor/demo/views.py
new file mode 100644
index 0000000000..1bdde9c242
--- /dev/null
+++ b/saleor/demo/views.py
@@ -0,0 +1,33 @@
+from django.shortcuts import render_to_response
+
+from ..graphql.views import API_PATH, GraphQLView
+
+EXAMPLE_QUERY = """# Welcome to Saleor GraphQL API!
+#
+# Type queries into this side of the screen, and you will see
+# intelligent typeaheads aware of the current GraphQL type schema
+# and live syntax and validation errors highlighted within the text.
+#
+# Here is an example query to fetch a list of products:
+#
+{
+ products(first: 5) {
+ edges {
+ node {
+ id
+ name
+ description
+ }
+ }
+ }
+}
+"""
+
+
+class DemoGraphQLView(GraphQLView):
+ def render_playground(self, request):
+ ctx = {
+ "query": EXAMPLE_QUERY,
+ "api_url": request.build_absolute_uri(str(API_PATH)),
+ }
+ return render_to_response("graphql/playground.html", ctx)
diff --git a/saleor/graphql/views.py b/saleor/graphql/views.py
index 262430b208..581667c18f 100644
--- a/saleor/graphql/views.py
+++ b/saleor/graphql/views.py
@@ -24,34 +24,13 @@ from graphql.error import (
from graphql.execution import ExecutionResult
from graphql_jwt.exceptions import PermissionDenied
-from ..core.utils import is_demo_mode, is_valid_ipv4, is_valid_ipv6
+from ..core.utils import is_valid_ipv4, is_valid_ipv6
API_PATH = SimpleLazyObject(lambda: reverse("api"))
unhandled_errors_logger = logging.getLogger("saleor.graphql.errors.unhandled")
handled_errors_logger = logging.getLogger("saleor.graphql.errors.handled")
-EXAMPLE_QUERY = """# Welcome to Saleor GraphQL API!
-#
-# Type queries into this side of the screen, and you will see
-# intelligent typeaheads aware of the current GraphQL type schema
-# and live syntax and validation errors highlighted within the text.
-#
-# Here is an example query to fetch a list of products:
-#
-{
- products(first: 5) {
- edges {
- node {
- id
- name
- description
- }
- }
- }
-}
-"""
-
def tracing_wrapper(execute, sql, params, many, context):
conn: DatabaseWrapper = context["connection"]
@@ -119,15 +98,7 @@ class GraphQLView(View):
return response
def render_playground(self, request):
- ctx = {}
- if is_demo_mode():
- ctx.update(
- {
- "query": EXAMPLE_QUERY,
- "api_url": request.build_absolute_uri(str(API_PATH)),
- }
- )
- return render_to_response("graphql/playground.html", ctx)
+ return render_to_response("graphql/playground.html", {})
def _handle_query(self, request: HttpRequest) -> JsonResponse:
try:
diff --git a/tests/api/test_view.py b/tests/api/test_view.py
index d1be93d1cb..0aa5a79347 100644
--- a/tests/api/test_view.py
+++ b/tests/api/test_view.py
@@ -5,12 +5,9 @@ import graphene
import pytest
from django.test import override_settings
+from saleor.demo.views import EXAMPLE_QUERY
from saleor.graphql.product.types import Product
-from saleor.graphql.views import (
- EXAMPLE_QUERY,
- handled_errors_logger,
- unhandled_errors_logger,
-)
+from saleor.graphql.views import handled_errors_logger, unhandled_errors_logger
from .conftest import API_PATH
from .utils import _get_graphql_content_from_response, get_graphql_content
diff --git a/tests/conftest.py b/tests/conftest.py
index 245b8a4aa3..a600ecbaa0 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -15,7 +15,6 @@ from django.core.files import File
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db import connection
from django.forms import ModelForm
-from django.test.client import Client
from django.test.utils import CaptureQueriesContext as BaseCaptureQueriesContext
from django_countries import countries
from PIL import Image
diff --git a/tests/test_core.py b/tests/test_core.py
index 4914f8c8ed..4d2974a01f 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -315,7 +315,10 @@ def test_cleardb_delete_staff_parameter(staff_user):
@override_settings(DEBUG=True)
-def test_cleardb_preserves_data(admin_user, site_settings):
+def test_cleardb_preserves_data(admin_user, service_account, site_settings, staff_user):
call_command("cleardb")
+ # These shouldn't be deleted when running `cleardb`.
admin_user.refresh_from_db()
+ service_account.refresh_from_db()
site_settings.refresh_from_db()
+ staff_user.refresh_from_db()