Use graphql-django-view to handle GraphQLView

This commit is contained in:
Jake 2015-11-13 16:53:35 -05:00
parent 5c4db65cc0
commit 5a1e014b9a
5 changed files with 15 additions and 69 deletions

View File

@ -1,67 +1,10 @@
import json
from django.conf import settings
from django.http import HttpResponse
from django.views.generic import View
from graphql.core.error import GraphQLError, format_error
from graphql_django_view import GraphQLView as BaseGraphQLView
def form_error(error):
if isinstance(error, GraphQLError):
return format_error(error)
return error
class GraphQLView(View):
schema = None
@staticmethod
def format_result(result):
data = {'data': result.data}
if result.errors:
data['errors'] = list(map(form_error, result.errors))
return data
def response_errors(self, *errors):
errors = [{
"message": str(e)
} for e in errors]
return HttpResponse(json.dumps({'errors': errors}), content_type='application/json')
def execute_query(self, request, query, *args, **kwargs):
if not query:
return self.response_errors(Exception("Must provide query string."))
else:
try:
result = self.schema.execute(query, *args, **kwargs)
data = self.format_result(result)
except Exception as e:
if settings.DEBUG:
raise e
return self.response_errors(e)
return HttpResponse(json.dumps(data), content_type='application/json')
def get(self, request, *args, **kwargs):
query = request.GET.get('query')
return self.execute_query(request, query or '')
@staticmethod
def get_content_type(request):
meta = request.META
return meta.get('CONTENT_TYPE', meta.get('HTTP_CONTENT_TYPE', ''))
def post(self, request, *args, **kwargs):
content_type = self.get_content_type(request)
if content_type == 'application/json':
try:
received_json_data = json.loads(request.body.decode())
query = received_json_data.get('query')
except ValueError:
return self.response_errors(ValueError("Malformed json body in the post data"))
elif content_type == 'application/graphql':
query = request.body.decode()
else:
query = request.POST.get('query') or request.GET.get('query')
return self.execute_query(request, query or '')
class GraphQLView(BaseGraphQLView):
def __init__(self, schema, **kwargs):
super(GraphQLView, self).__init__(
schema=schema.schema,
executor=schema.executor,
**kwargs
)

View File

@ -56,7 +56,8 @@ setup(
install_requires=[
'six>=1.10.0',
'blinker',
'graphql-core==0.4.7b0',
'graphql-core==0.4.7b2',
'graphql-django-view>=1.0.0',
'graphql-relay==0.3.3'
],
tests_require=[

View File

@ -23,7 +23,8 @@ class Human(DjangoNode):
class Meta:
model = Article
def resolve_raises(self, *args):
@staticmethod
def resolve_raises(*args):
raise Exception("This field should raise exception")
def get_node(self, id):

View File

@ -26,7 +26,7 @@ def test_client_post_malformed_json(settings, client):
response = client.post('/graphql', 'MALFORMED', 'application/json')
json_response = format_response(response)
assert json_response == {'errors': [
{'message': 'Malformed json body in the post data'}]}
{'message': 'POST body sent invalid JSON.'}]}
def test_client_post_empty_query_json(settings, client):

View File

@ -7,7 +7,8 @@ deps=
pytest>=2.7.2
django>=1.8.0,<1.9
pytest-django
graphql-core==0.4.7b0
graphql-django-view>=1.0.0
graphql-core==0.4.7b2
graphql-relay==0.3.3
six
blinker