1
1
import json
2
+ from functools import partial
2
3
3
4
from flask import Response , request
4
5
from flask .views import View
5
6
6
7
from graphql .type .schema import GraphQLSchema
7
- from graphql_server import run_http_query , HttpQueryError , default_format_error , load_json_body , format_execution_result
8
+ from graphql_server import run_http_query , HttpQueryError , default_format_error , load_json_body , encode_execution_results , json_encode
8
9
9
10
from .render_graphiql import render_graphiql
10
11
@@ -54,8 +55,10 @@ def render_graphiql(self, params, result):
54
55
graphiql_template = self .graphiql_template ,
55
56
)
56
57
58
+ format_error = staticmethod (default_format_error )
59
+ encode = staticmethod (json_encode )
60
+
57
61
def dispatch_request (self ):
58
-
59
62
try :
60
63
request_method = request .method .lower ()
61
64
data = self .parse_body ()
@@ -72,24 +75,19 @@ def dispatch_request(self):
72
75
query_data = request .args ,
73
76
batch_enabled = self .batch ,
74
77
catch = catch ,
78
+
75
79
# Execute options
76
80
root_value = self .get_root_value (),
77
81
context_value = self .get_context (),
78
82
middleware = self .get_middleware (),
79
83
executor = self .get_executor (),
80
84
)
81
- responses = [
82
- format_execution_result (execution_result , default_format_error )
83
- for execution_result in execution_results
84
- ]
85
- result , status_codes = zip (* responses )
86
- status_code = max (status_codes )
87
-
88
- # If is not batch
89
- if not isinstance (data , list ):
90
- result = result [0 ]
91
-
92
- result = self .json_encode (result , pretty )
85
+ result , status_code = encode_execution_results (
86
+ execution_results ,
87
+ is_batch = isinstance (data , list ),
88
+ format_error = self .format_error ,
89
+ encode = partial (self .encode , pretty = pretty )
90
+ )
93
91
94
92
if show_graphiql :
95
93
return self .render_graphiql (
@@ -105,8 +103,8 @@ def dispatch_request(self):
105
103
106
104
except HttpQueryError as e :
107
105
return Response (
108
- self .json_encode ({
109
- 'errors' : [default_format_error (e )]
106
+ self .encode ({
107
+ 'errors' : [self . format_error (e )]
110
108
}),
111
109
status = e .status_code ,
112
110
headers = e .headers ,
@@ -131,17 +129,6 @@ def parse_body(self):
131
129
132
130
return {}
133
131
134
- @staticmethod
135
- def json_encode (data , pretty = False ):
136
- if not pretty :
137
- return json .dumps (data , separators = (',' , ':' ))
138
-
139
- return json .dumps (
140
- data ,
141
- indent = 2 ,
142
- separators = (',' , ': ' )
143
- )
144
-
145
132
def should_display_graphiql (self ):
146
133
if not self .graphiql or 'raw' in request .args :
147
134
return False
0 commit comments