forked from graphql-python/graphql-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraphqlview.py
209 lines (179 loc) · 6.97 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
import asyncio
import copy
from collections.abc import MutableMapping
from functools import partial
from typing import List
from flask import Response, render_template_string, request
from flask.views import View
from graphql import pyutils, specified_rules
from graphql.error import GraphQLError
from graphql.type.schema import GraphQLSchema
from graphql_server import (
GraphQLParams,
HttpQueryError,
_check_jinja,
encode_execution_results,
format_error_default,
json_encode,
load_json_body,
run_http_query,
)
from graphql_server.render_graphiql import (
GraphiQLConfig,
GraphiQLData,
GraphiQLOptions,
render_graphiql_sync,
)
class GraphQLView(View):
schema = None
root_value = None
context = None
pretty = False
graphiql = False
graphiql_version = None
graphiql_template = None
graphiql_html_title = None
middleware = None
validation_rules = None
execution_context_class = None
batch = False
jinja_env = None
subscriptions = None
headers = None
default_query = None
header_editor_enabled = None
should_persist_headers = None
methods = ["GET", "POST", "PUT", "DELETE"]
format_error = staticmethod(format_error_default)
encode = staticmethod(json_encode)
def __init__(self, **kwargs):
super(GraphQLView, self).__init__()
for key, value in kwargs.items():
if hasattr(self, key):
setattr(self, key, value)
if not isinstance(self.schema, GraphQLSchema):
# maybe the GraphQL schema is wrapped in a Graphene schema
self.schema = getattr(self.schema, "graphql_schema", None)
if not isinstance(self.schema, GraphQLSchema):
raise TypeError("A Schema is required to be provided to GraphQLView.")
if self.jinja_env is not None:
_check_jinja(self.jinja_env)
def get_root_value(self):
return self.root_value
def get_context(self):
context = (
copy.copy(self.context)
if self.context is not None and isinstance(self.context, MutableMapping)
else {}
)
if isinstance(context, MutableMapping) and "request" not in context:
context.update({"request": request})
return context
def get_middleware(self):
return self.middleware
def get_validation_rules(self):
if self.validation_rules is None:
return specified_rules
return self.validation_rules
def get_execution_context_class(self):
return self.execution_context_class
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")
all_params: List[GraphQLParams]
execution_results, all_params = run_http_query(
self.schema,
request_method,
data,
query_data=request.args,
batch_enabled=self.batch,
catch=catch,
# Execute options
root_value=self.get_root_value(),
context_value=self.get_context(),
middleware=self.get_middleware(),
validation_rules=self.get_validation_rules(),
execution_context_class=self.get_execution_context_class(),
run_sync=False,
)
# This is (almost) copied from graphql_server.aiohttp.GraphQLView
# It is a bit weird as it originally calls await in a loop which
# a bit breaks the gains from doing operations asynchronously...
# But maybe it is required for correctness to execute those
# operations like that, so leaving it.
exec_res = [
ex
if ex is None or not pyutils.is_awaitable(ex)
else asyncio.run(ex)
for ex in execution_results
]
result, status_code = encode_execution_results(
exec_res,
is_batch=isinstance(data, list),
format_error=self.format_error,
encode=partial(self.encode, pretty=pretty), # noqa
)
if show_graphiql:
graphiql_data = GraphiQLData(
result=result,
query=getattr(all_params[0], "query"),
variables=getattr(all_params[0], "variables"),
operation_name=getattr(all_params[0], "operation_name"),
subscription_url=self.subscriptions,
headers=self.headers,
)
graphiql_config = GraphiQLConfig(
graphiql_version=self.graphiql_version,
graphiql_template=self.graphiql_template,
graphiql_html_title=self.graphiql_html_title,
jinja_env=self.jinja_env,
)
graphiql_options = GraphiQLOptions(
default_query=self.default_query,
header_editor_enabled=self.header_editor_enabled,
should_persist_headers=self.should_persist_headers,
)
source = render_graphiql_sync(
data=graphiql_data, config=graphiql_config, options=graphiql_options
)
return render_template_string(source)
return Response(result, status=status_code, content_type="application/json")
except HttpQueryError as e:
parsed_error = GraphQLError(e.message)
return Response(
self.encode(dict(errors=[self.format_error(parsed_error)])),
status=e.status_code,
headers=e.headers,
content_type="application/json",
)
@staticmethod
def parse_body():
# 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 in (
"application/x-www-form-urlencoded",
"multipart/form-data",
):
return request.form
return {}
def should_display_graphiql(self):
if not self.graphiql or "raw" in request.args:
return False
return self.request_wants_html()
@staticmethod
def request_wants_html():
best = request.accept_mimetypes.best_match(["application/json", "text/html"])
return (
best == "text/html"
and request.accept_mimetypes[best]
> request.accept_mimetypes["application/json"]
)