Skip to content

Commit a3f84aa

Browse files
committed
Added the ability to specify a JSON decoder
1 parent 8077fee commit a3f84aa

File tree

3 files changed

+22
-3
lines changed

3 files changed

+22
-3
lines changed

flask_graphql/graphqlview.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ class GraphQLView(View):
3434
middleware = None
3535
batch = False
3636
json_encoder = None
37+
json_decoder = None
3738

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

@@ -156,7 +157,7 @@ def parse_body(self, request):
156157

157158
elif content_type == 'application/json':
158159
try:
159-
request_json = json.loads(request.data.decode('utf8'))
160+
request_json = json.loads(request.data.decode('utf8'), cls=self.json_decoder)
160161
if self.batch:
161162
assert isinstance(request_json, list)
162163
else:

tests/encoder.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
1-
from json import JSONEncoder
1+
from json import JSONEncoder, JSONDecoder
2+
from json.decoder import WHITESPACE
23

34

45
class TestJSONEncoder(JSONEncoder):
56
def encode(self, o):
67
return 'TESTSTRING'
8+
9+
10+
class TestJSONDecoder(JSONDecoder):
11+
def decode(self, s, _w=WHITESPACE.match):
12+
return {'query': '{test}'}

tests/test_graphqlview.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
from urllib.parse import urlencode
1313

1414
from .app import create_app
15-
from .encoder import TestJSONEncoder
15+
from .encoder import TestJSONEncoder, TestJSONDecoder
1616
from flask import url_for
1717

1818

@@ -541,3 +541,15 @@ def test_custom_encoder(client):
541541

542542
# TestJSONEncoder just encodes everything to 'TESTSTRING'
543543
assert response.data.decode() == 'TESTSTRING'
544+
545+
546+
@pytest.mark.parametrize('app', [create_app(json_decoder=TestJSONDecoder)])
547+
def test_custom_decoder(client):
548+
# The submitted data here of 'TEST' is clearly not valid JSON. The TestJSONDecoder will
549+
# decode this into valid JSON with a valid gql query.
550+
response = client.post(url_string(), data='TEST', content_type='application/json')
551+
552+
assert response.status_code == 200
553+
assert response_json(response) == {
554+
'data': {'test': "Hello World"}
555+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy