Skip to content

Commit 8077fee

Browse files
committed
Added the ability to specify the JSON encoder
1 parent 2825345 commit 8077fee

File tree

3 files changed

+21
-5
lines changed

3 files changed

+21
-5
lines changed

Diff for: flask_graphql/graphqlview.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ class GraphQLView(View):
3333
graphiql_template = None
3434
middleware = None
3535
batch = False
36+
json_encoder = None
3637

3738
methods = ['GET', 'POST', 'PUT', 'DELETE']
3839

@@ -142,10 +143,10 @@ def get_response(self, request, data, show_graphiql=False):
142143
def json_encode(self, request, d, show_graphiql=False):
143144
pretty = self.pretty or show_graphiql or request.args.get('pretty')
144145
if not pretty:
145-
return json.dumps(d, separators=(',', ':'))
146+
return json.dumps(d, separators=(',', ':'), cls=self.json_encoder)
146147

147-
return json.dumps(d, sort_keys=True,
148-
indent=2, separators=(',', ': '))
148+
return json.dumps(d, sort_keys=True, indent=2,
149+
separators=(',', ': '), cls=self.json_encoder)
149150

150151
# noinspection PyBroadException
151152
def parse_body(self, request):

Diff for: tests/encoder.py

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
from json import JSONEncoder
2+
3+
4+
class TestJSONEncoder(JSONEncoder):
5+
def encode(self, o):
6+
return 'TESTSTRING'

Diff for: tests/test_graphqlview.py

+11-2
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from urllib.parse import urlencode
1313

1414
from .app import create_app
15+
from .encoder import TestJSONEncoder
1516
from flask import url_for
1617

1718

@@ -500,8 +501,8 @@ def test_batch_supports_post_json_query_with_json_variables(client):
500501
'payload': { 'data': {'test': "Hello Dolly"} },
501502
'status': 200,
502503
}]
503-
504-
504+
505+
505506
@pytest.mark.parametrize('app', [create_app(batch=True)])
506507
def test_batch_allows_post_with_operation_name(client):
507508
response = client.post(
@@ -532,3 +533,11 @@ def test_batch_allows_post_with_operation_name(client):
532533
},
533534
'status': 200,
534535
}]
536+
537+
538+
@pytest.mark.parametrize('app', [create_app(json_encoder=TestJSONEncoder)])
539+
def test_custom_encoder(client):
540+
response = client.get(url_string(query='{test}'))
541+
542+
# TestJSONEncoder just encodes everything to 'TESTSTRING'
543+
assert response.data.decode() == 'TESTSTRING'

0 commit comments

Comments
 (0)