-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathgraphqlview.py
More file actions
244 lines (188 loc) · 7.33 KB
/
graphqlview.py
File metadata and controls
244 lines (188 loc) · 7.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
from functools import partial
from flask import Response, request
from flask.views import View
from graphql.type.schema import GraphQLSchema
from graphql_server import (HttpQueryError, default_format_error,
encode_execution_results, json_encode,
load_json_body, run_http_query)
from .render_graphiql import render_graphiql
class GraphQLView(View):
schema = None
executor = None
root_value = None
pretty = False
graphiql = False
backend = None
graphiql_version = None
graphiql_template = None
graphiql_html_title = None
middleware = None
batch = False
methods = ['GET', 'POST', 'PUT', 'DELETE']
def __init__(self, **kwargs):
super(GraphQLView, self).__init__()
for key, value in kwargs.items():
if hasattr(self, key):
setattr(self, key, value)
assert isinstance(self.schema, GraphQLSchema), 'A Schema is required to be provided to GraphQLView.'
# noinspection PyUnusedLocal
def get_root_value(self):
return self.root_value
def get_context(self):
return request
def get_middleware(self):
return self.middleware
def get_backend(self):
return self.backend
def get_executor(self):
return self.executor
def render_graphiql(self, params, result):
return render_graphiql(
params=params,
result=result,
graphiql_version=self.graphiql_version,
graphiql_template=self.graphiql_template,
graphiql_html_title=self.graphiql_html_title,
)
format_error = staticmethod(default_format_error)
encode = staticmethod(json_encode)
def dispatch_request(self):
try:
request_method = request.method.lower()
data = self.parse_body()
show_graphiql = request_method == 'get' and self.should_display_graphiql()
catch = show_graphiql
pretty = self.pretty or show_graphiql or request.args.get('pretty')
extra_options = {}
executor = self.get_executor()
if executor:
# We only include it optionally since
# executor is not a valid argument in all backends
extra_options['executor'] = executor
execution_results, all_params = run_http_query(
self.schema,
request_method,
data,
query_data=request.args,
batch_enabled=self.batch,
catch=catch,
backend=self.get_backend(),
# Execute options
root=self.get_root_value(),
context=self.get_context(),
middleware=self.get_middleware(),
**extra_options
)
result, status_code = encode_execution_results(
execution_results,
is_batch=isinstance(data, list),
format_error=self.format_error,
encode=partial(self.encode, pretty=pretty)
)
if show_graphiql:
return self.render_graphiql(
params=all_params[0],
result=result
)
return Response(
result,
status=status_code,
content_type='application/json'
)
except HttpQueryError as e:
return Response(
self.encode({
'errors': [self.format_error(e)]
}),
status=e.status_code,
headers=e.headers,
content_type='application/json'
)
# Flask
# noinspection PyBroadException
def parse_body(self):
# We use mimetype here since we don't need the other
# information provided by content_type
content_type = request.mimetype
if content_type == 'application/graphql':
return {'query': request.data.decode('utf8')}
elif content_type == 'application/json':
return load_json_body(request.data.decode('utf8'))
elif content_type == 'application/x-www-form-urlencoded':
return request.form
elif content_type == 'multipart/form-data':
# --------------------------------------------------------
# See spec: https://github.com/jaydenseric/graphql-multipart-request-spec
#
# When processing multipart/form-data, we need to take
# files (from "parts") and place them in the "operations"
# data structure (list or dict) according to the "map".
# --------------------------------------------------------
operations = load_json_body(request.form['operations'])
files_map = load_json_body(request.form['map'])
return place_files_in_operations(
operations, files_map, request.files)
return {}
def should_display_graphiql(self):
if not self.graphiql or 'raw' in request.args:
return False
return self.request_wants_html()
def request_wants_html(self):
best = request.accept_mimetypes \
.best_match(['application/json', 'text/html'])
return best == 'text/html' and \
request.accept_mimetypes[best] > \
request.accept_mimetypes['application/json']
def place_files_in_operations(operations, files_map, files):
"""Place files from multipart reuqests inside operations.
Args:
operations:
Either a dict or a list of dicts, containing GraphQL
operations to be run.
files_map:
A dictionary defining the mapping of files into "paths"
inside the operations data structure.
Keys are file names from the "files" dict, values are
lists of dotted paths describing where files should be
placed.
files:
A dictionary mapping file names to FileStorage instances.
Returns:
A structure similar to operations, but with FileStorage
instances placed appropriately.
"""
# operations: dict or list
# files_map: {filename: [path, path, ...]}
# files: {filename: FileStorage}
fmap = []
for key, values in files_map.items():
for val in values:
path = val.split('.')
fmap.append((path, key))
return _place_files_in_operations(operations, fmap, files)
def _place_files_in_operations(ops, fmap, fobjs):
for path, fkey in fmap:
ops = _place_file_in_operations(ops, path, fobjs[fkey])
return ops
def _place_file_in_operations(ops, path, obj):
if len(path) == 0:
return obj
if isinstance(ops, list):
key = int(path[0])
sub = _place_file_in_operations(ops[key], path[1:], obj)
return _insert_in_list(ops, key, sub)
if isinstance(ops, dict):
key = path[0]
sub = _place_file_in_operations(ops[key], path[1:], obj)
return _insert_in_dict(ops, key, sub)
raise TypeError('Expected ops to be list or dict')
def _insert_in_dict(dct, key, val):
new_dict = dct.copy()
new_dict[key] = val
return new_dict
def _insert_in_list(lst, key, val):
new_list = []
new_list.extend(lst[:key])
new_list.append(val)
new_list.extend(lst[key + 1:])
return new_list