-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathgraphqlview.py
212 lines (185 loc) · 7.23 KB
/
graphqlview.py
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
from collections import Mapping
from functools import partial
from aiohttp import web
from promise import Promise
from graphql.type.schema import GraphQLSchema
from graphql.execution.executors.asyncio import AsyncioExecutor
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: # pylint: disable = too-many-instance-attributes
def __init__(
self,
schema=None,
executor=None,
root_value=None,
context=None,
pretty=False,
graphiql=False,
graphiql_version=None,
graphiql_template=None,
middleware=None,
batch=False,
jinja_env=None,
max_age=86400,
encoder=None,
error_formatter=None,
enable_async=True,
):
# pylint: disable=too-many-arguments
# pylint: disable=too-many-locals
self.schema = schema
self.executor = executor
self.root_value = root_value
self.context = context
self.pretty = pretty
self.graphiql = graphiql
self.graphiql_version = graphiql_version
self.graphiql_template = graphiql_template
self.middleware = middleware
self.batch = batch
self.jinja_env = jinja_env
self.max_age = max_age
self.encoder = encoder or json_encode
self.error_formatter = error_formatter or default_format_error
self.enable_async = enable_async and isinstance(
self.executor,
AsyncioExecutor,
)
assert isinstance(self.schema, GraphQLSchema), \
'A Schema is required to be provided to GraphQLView.'
def get_context(self, request):
if self.context and isinstance(self.context, Mapping):
context = self.context.copy()
else:
context = {}
if isinstance(context, Mapping) and 'request' not in context:
context.update({'request': request})
return context
async def parse_body(self, request):
if request.content_type == 'application/graphql':
r_text = await request.text()
return {'query': r_text}
elif request.content_type == 'application/json':
text = await request.text()
return load_json_body(text)
elif request.content_type in (
'application/x-www-form-urlencoded',
'multipart/form-data',
):
# TODO: seems like a multidict would be more appropriate
# than casting it and de-duping variables. Alas, it's what
# graphql-python wants.
return dict(await request.post())
return {}
def render_graphiql(self, params, result):
return render_graphiql(
jinja_env=self.jinja_env,
params=params,
result=result,
graphiql_version=self.graphiql_version,
graphiql_template=self.graphiql_template,
)
def is_graphiql(self, request):
return all([
self.graphiql,
request.method.lower() == 'get',
'raw' not in request.query,
any([
'text/html' in request.headers.get('accept', {}),
'*/*' in request.headers.get('accept', {}),
]),
])
def is_pretty(self, request):
return any([
self.pretty,
self.is_graphiql(request),
request.query.get('pretty'),
])
async def __call__(self, request):
try:
data = await self.parse_body(request)
request_method = request.method.lower()
is_graphiql = self.is_graphiql(request)
is_pretty = self.is_pretty(request)
if request_method == 'options':
return self.process_preflight(request)
execution_results, all_params = run_http_query(
self.schema,
request_method,
data,
query_data=request.query,
batch_enabled=self.batch,
catch=is_graphiql,
# Execute options
return_promise=self.enable_async,
root_value=self.root_value,
context_value=self.get_context(request),
middleware=self.middleware,
executor=self.executor,
)
awaited_execution_results = await Promise.all(execution_results)
result, status_code = encode_execution_results(
awaited_execution_results,
is_batch=isinstance(data, list),
format_error=self.error_formatter,
encode=partial(self.encoder, pretty=is_pretty),
)
if is_graphiql:
return await self.render_graphiql(
params=all_params[0],
result=result,
)
return web.Response(
text=result,
status=status_code,
content_type='application/json',
)
except HttpQueryError as err:
if err.headers and 'Allow' in err.headers:
# bug in graphql_server.execute_graphql_request
# https://github.com/graphql-python/graphql-server-core/pull/4
if isinstance(err.headers['Allow'], list):
err.headers['Allow'] = ', '.join(err.headers['Allow'])
return web.Response(
text=self.encoder({
'errors': [self.error_formatter(err)]
}),
status=err.status_code,
headers=err.headers,
content_type='application/json',
)
def process_preflight(self, request):
""" Preflight request support for apollo-client
https://www.w3.org/TR/cors/#resource-preflight-requests """
headers = request.headers
origin = headers.get('Origin', '')
method = headers.get('Access-Control-Request-Method', '').upper()
accepted_methods = ['GET', 'POST', 'PUT', 'DELETE']
if method and method in accepted_methods:
return web.Response(
status=200,
headers={
'Access-Control-Allow-Origin': origin,
'Access-Control-Allow-Methods': ', '.join(accepted_methods),
'Access-Control-Max-Age': str(self.max_age),
}
)
return web.Response(status=400)
@classmethod
def attach(cls, app, *, route_path='/graphql', route_name='graphql',
**kwargs):
view = cls(**kwargs)
#app.router.add_route('*', route_path, view, name=route_name)
for method in ('GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD'): # no OPTIONS
app.router.add_route(method, route_path, view, name=route_name)
# apparently this is just plain missing otherwise?
if 'graphiql' in kwargs and kwargs['graphiql']:
for method in ('GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD'): # no OPTIONS
app.router.add_route(method, '/graphiql', view, name='graphiql')