Skip to content

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

Replace Graphene view with a custom one

Patryk Zawadzkibc0b9a9fecc4
diff --git a/saleor/graphql/file_upload/views.py b/saleor/graphql/file_upload/views.py
index 705dd310de..323e248225 100644
--- a/saleor/graphql/file_upload/views.py
+++ b/saleor/graphql/file_upload/views.py
@@ -1,58 +1,170 @@
import json
from django.conf import settings
-from graphene_django.views import GraphQLView
+from django.http import HttpRequest, HttpResponseNotAllowed, JsonResponse
+from django.shortcuts import render_to_response
+from django.views.generic import View
+from graphene_django.settings import graphene_settings
+from graphene_django.views import instantiate_middleware
+from graphql import get_default_backend
+from graphql.error import GraphQLError, format_error as format_graphql_error
+from graphql.execution import ExecutionResult
+
+
+class FileUploadGraphQLView(View):
+ # This class was inspired by the `FileUploadGraphQLView` class from
+ # https://github.com/lmcgartland/graphene-file-upload
+ schema = None
+ executor = None
+ backend = None
+ middleware = None
+ root_value = None
+
+ def __init__(
+ self,
+ schema=None,
+ executor=None,
+ middleware=None,
+ root_value=None,
+ backend=None):
+ if schema is None:
+ schema = graphene_settings.SCHEMA
+ if backend is None:
+ backend = get_default_backend()
+ if middleware is None:
+ middleware = graphene_settings.MIDDLEWARE
+ self.schema = self.schema or schema
+ if middleware is not None:
+ self.middleware = list(instantiate_middleware(middleware))
+ self.executor = executor
+ self.root_value = root_value
+ self.backend = backend
-# This class is modified verion of the `ModifiedGraphQLView` class from
-# `graphene-file-upload` (https://github.com/lmcgartland/graphene-file-upload).
-
-
-class FileUploadGraphQLView(GraphQLView):
def dispatch(self, request, *args, **kwargs):
# Handle options method the GraphQlView restricts it.
+ if request.method == 'GET':
+ return render_to_response('graphql/playground.html')
if request.method == 'OPTIONS':
response = self.options(request, *args, **kwargs)
+ elif request.method == 'POST':
+ response = self.handle_query(request, *args, **kwargs)
else:
- response = super().dispatch(request, *args, **kwargs)
+ return HttpResponseNotAllowed(
+ ['GET', 'OPTIONS', 'POST'])
# Add access control headers
- response['Access-Control-Allow-Origin'] = ','.join(
- settings.ALLOWED_HOSTS)
+ response['Access-Control-Allow-Origin'] = (
+ settings.ALLOWED_GRAPHQL_ORIGINS)
response['Access-Control-Allow-Methods'] = 'POST, OPTIONS'
response['Access-Control-Allow-Headers'] = (
'Origin, Content-Type, Accept, Authorization')
return response
- @staticmethod
- def get_graphql_params(request, data):
- content_type = GraphQLView.get_content_type(request)
-
- # Only check multipart/form-data if content_type is not None (this is
- # not checked in the original version from `graphene-file-upload`).
- if content_type and 'multipart/form-data' in content_type:
- query, variables, operation_name, id = super(
- FileUploadGraphQLView,
- FileUploadGraphQLView).get_graphql_params(request, data)
- operations = data.get('operations')
- files_map = data.get('map')
- try:
- operations = json.loads(operations)
- files_map = json.loads(files_map)
- variables = operations.get('variables')
- for file_key in files_map:
- # file key is which file it is in the form-data
- file_instances = files_map[file_key]
- for file_instance in file_instances:
- test = obj_set(
- operations, file_instance, file_key, False)
- query = operations.get('query')
- variables = operations.get('variables')
- except Exception as e:
- raise e
+ def handle_query(self, request: HttpRequest, *args, **kwargs):
+ try:
+ data = self.parse_body(request)
+ except ValueError as e:
+ return JsonResponse(
+ data={
+ 'errors': [self.format_error('Unable to parse query.')]},
+ status=400)
+ if isinstance(data, list):
+ responses = [self.get_response(request, entry) for entry in data]
+ result = [response for response, code in responses]
+ status_code = max((code for response, code in responses),
+ default=200)
else:
- query, variables, operation_name, id = super(
- FileUploadGraphQLView,
- FileUploadGraphQLView).get_graphql_params(request, data)
- return query, variables, operation_name, id
+ result, status_code = self.get_response(request, data)
+ return JsonResponse(
+ data=result,
+ status=status_code)
+
+ def get_response(self, request: HttpRequest, data: dict):
+ query, variables, operation_name = self.get_graphql_params(
+ request, data)
+ execution_result = self.execute_graphql_request(
+ request, query, variables, operation_name)
+ status_code = 200
+ if execution_result:
+ response = {}
+ if execution_result.errors:
+ response['errors'] = [
+ self.format_error(e) for e in execution_result.errors]
+ if execution_result.invalid:
+ status_code = 400
+ else:
+ response['data'] = execution_result.data
+ result = response
+ else:
+ result = None
+ return result, status_code
+
+ def get_root_value(self, request: HttpRequest):
+ return self.root_value
+
+ def execute_graphql_request(
+ self, request: HttpRequest, query: str, variables: dict,
+ operation_name: str):
+ if not query:
+ return ExecutionResult(
+ errors=[ValueError('Must provide a query string.')],
+ invalid=True)
+ try:
+ document = self.backend.document_from_string(self.schema, query)
+ except ValueError as e:
+ return ExecutionResult(errors=[e], invalid=True)
+ extra_options = {}
+ if self.executor:
+ # We only include it optionally since
+ # executor is not a valid argument in all backends
+ extra_options['executor'] = self.executor
+ try:
+ return document.execute(
+ root=self.get_root_value(request),
+ variables=variables,
+ operation_name=operation_name,
+ context=request,
+ middleware=self.middleware,
+ **extra_options)
+ except Exception as e:
+ return ExecutionResult(errors=[e], invalid=True)
+
+ @staticmethod
+ def parse_body(request: HttpRequest):
+ content_type = request.content_type
+ 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)
+ if content_type in ['application/x-www-form-urlencoded',
+ 'multipart/form-data']:
+ return request.POST
+ return {}
+
+ @staticmethod
+ def get_graphql_params(request: HttpRequest, data: dict):
+ query = data.get('query')
+ variables = data.get('variables')
+ operation_name = data.get('operationName')
+ if operation_name == 'null':
+ operation_name = None
+ if request.content_type == 'multipart/form-data':
+ operations = json.loads(data.get('operations', '{}'))
+ files_map = json.loads(data.get('map', '{}'))
+ for file_key in files_map:
+ # file key is which file it is in the form-data
+ file_instances = files_map[file_key]
+ for file_instance in file_instances:
+ test = obj_set(operations, file_instance, file_key, False)
+ query = operations.get('query')
+ variables = operations.get('variables')
+ return query, variables, operation_name
+
+ @staticmethod
+ def format_error(error):
+ if isinstance(error, GraphQLError):
+ return format_graphql_error(error)
+ return {'message': str(error)}
def getKey(key):
diff --git a/saleor/settings.py b/saleor/settings.py
index ce7dd86a6f..0bdce6d7b6 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -371,6 +371,7 @@ TEST_RUNNER = 'tests.runner.PytestTestRunner'
ALLOWED_HOSTS = get_list(
os.environ.get('ALLOWED_HOSTS', 'localhost,127.0.0.1'))
+ALLOWED_GRAPHQL_ORIGINS = os.environ.get('ALLOWED_GRAPHQL_ORIGINS', '*')
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
diff --git a/saleor/urls.py b/saleor/urls.py
index 1c770e607d..78f2b4244f 100644
--- a/saleor/urls.py
+++ b/saleor/urls.py
@@ -27,7 +27,7 @@ non_translatable_urlpatterns = [
url(r'^dashboard/',
include((dashboard_urls, 'dashboard'), namespace='dashboard')),
url(r'^graphql/', csrf_exempt(FileUploadGraphQLView.as_view(
- schema=schema, graphiql=settings.DEBUG)), name='api'),
+ schema=schema)), name='api'),
url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps},
name='django.contrib.sitemaps.views.sitemap'),
url(r'^i18n/$', set_language, name='set_language'),
diff --git a/templates/graphql/playground.html b/templates/graphql/playground.html
new file mode 100644
index 0000000000..301d8bfc88
--- /dev/null
+++ b/templates/graphql/playground.html
@@ -0,0 +1,51 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset=utf-8/>
+ <meta name="viewport" content="user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, minimal-ui">
+ <title>GraphQL Playground</title>
+ <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/[email protected]/build/static/css/index.css" />
+ <link rel="shortcut icon" href="//cdn.jsdelivr.net/npm/[email protected]/build/favicon.png" />
+ <script src="//cdn.jsdelivr.net/npm/[email protected]/build/static/js/middleware.js"></script>
+</head>
+<body>
+ <div id="root">
+ <style>
+ body {
+ background-color: rgb(23, 42, 58);
+ font-family: Open Sans, sans-serif;
+ height: 90vh;
+ }
+ #root {
+ height: 100%;
+ width: 100%;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ }
+ .loading {
+ font-size: 32px;
+ font-weight: 200;
+ color: rgba(255, 255, 255, .6);
+ margin-left: 20px;
+ }
+ img {
+ width: 78px;
+ height: 78px;
+ }
+ .title {
+ font-weight: 400;
+ }
+ </style>
+ <img src='//cdn.jsdelivr.net/npm/graphql-playground-react/build/logo.png' alt=''>
+ <div class="loading"> Loading
+ <span class="title">GraphQL Playground</span>
+ </div>
+ </div>
+ <script>window.addEventListener('load', function (event) {
+ GraphQLPlayground.init(document.getElementById('root'), {
+ // options as 'endpoint' belong here
+ })
+ })</script>
+</body>
+</html>
diff --git a/tests/api/conftest.py b/tests/api/conftest.py
index 23b4593075..b4e5b41f45 100644
--- a/tests/api/conftest.py
+++ b/tests/api/conftest.py
@@ -49,7 +49,7 @@ class ApiClient(Client):
"""
data = {'query': query}
if variables is not None:
- data['variables'] = json.dumps(variables)
+ data['variables'] = variables
if data:
data = json.dumps(data)
kwargs['content_type'] = 'application/json'
diff --git a/tests/api/test_account.py b/tests/api/test_account.py
index 9cfd8abffa..35241b937d 100644
--- a/tests/api/test_account.py
+++ b/tests/api/test_account.py
@@ -28,7 +28,7 @@ def test_create_token_mutation(admin_client, staff_user):
}
}
"""
- variables = json.dumps({'email': staff_user.email, 'password': 'password'})
+ variables = {'email': staff_user.email, 'password': 'password'}
response = admin_client.post(
reverse('api'), json.dumps({'query': query, 'variables': variables}),
content_type='application/json')
@@ -37,8 +37,7 @@ def test_create_token_mutation(admin_client, staff_user):
assert token_data['token']
assert not token_data['errors']
- incorrect_variables = json.dumps(
- {'email': staff_user.email, 'password': 'incorrect'})
+ incorrect_variables = {'email': staff_user.email, 'password': 'incorrect'}
response = admin_client.post(
reverse('api'),
json.dumps({'query': query, 'variables': incorrect_variables}),