-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathsync_base_view.py
More file actions
276 lines (230 loc) · 9.14 KB
/
sync_base_view.py
File metadata and controls
276 lines (230 loc) · 9.14 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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import abc
import json
from collections.abc import Mapping
from typing import (
Any,
Callable,
Generic,
Literal,
Optional,
Union,
)
from graphql import ExecutionResult, GraphQLError
from graphql.language import OperationType
from graphql.type import GraphQLSchema
from graphql_server import execute_sync
from graphql_server.exceptions import GraphQLValidationError, InvalidOperationTypeError
from graphql_server.file_uploads.utils import replace_placeholders_with_files
from graphql_server.http import (
GraphQLHTTPResponse,
GraphQLRequestData,
process_result,
)
from graphql_server.http.ides import GraphQL_IDE
from graphql_server.http.types import operation_type_from_http
from graphql_server.types.unset import UNSET
from .base import BaseView
from .exceptions import HTTPException
from .parse_content_type import parse_content_type
from .types import HTTPMethod, QueryParams
from .typevars import Context, Request, Response, RootValue, SubResponse
class SyncHTTPRequestAdapter(abc.ABC):
@property
@abc.abstractmethod
def query_params(self) -> QueryParams: ...
@property
@abc.abstractmethod
def body(self) -> Union[str, bytes]: ...
@property
@abc.abstractmethod
def method(self) -> HTTPMethod: ...
@property
@abc.abstractmethod
def headers(self) -> Mapping[str, str]: ...
@property
@abc.abstractmethod
def content_type(self) -> Optional[str]: ...
@property
@abc.abstractmethod
def post_data(self) -> Mapping[str, Union[str, bytes]]: ...
@property
@abc.abstractmethod
def files(self) -> Mapping[str, Any]: ...
class SyncBaseHTTPView(
abc.ABC,
BaseView[Request],
Generic[Request, Response, SubResponse, Context, RootValue],
):
schema: GraphQLSchema
graphiql: Optional[bool]
graphql_ide: Optional[GraphQL_IDE]
request_adapter_class: Callable[[Request], SyncHTTPRequestAdapter]
# Methods that need to be implemented by individual frameworks
@property
@abc.abstractmethod
def allow_queries_via_get(self) -> bool: ...
@abc.abstractmethod
def get_sub_response(self, request: Request) -> SubResponse: ...
@abc.abstractmethod
def get_context(self, request: Request, response: SubResponse) -> Context: ...
@abc.abstractmethod
def get_root_value(self, request: Request) -> Optional[RootValue]: ...
@abc.abstractmethod
def create_response(
self,
response_data: GraphQLHTTPResponse,
sub_response: SubResponse,
is_strict: bool,
) -> Response: ...
@abc.abstractmethod
def render_graphql_ide(
self, request: Request, request_data: GraphQLRequestData
) -> Response: ...
def execute_operation(
self,
request_adapter: SyncHTTPRequestAdapter,
request_data: GraphQLRequestData,
context: Context,
root_value: Optional[RootValue],
allowed_operation_types: set[OperationType],
) -> ExecutionResult:
assert self.schema
return execute_sync(
schema=self.schema,
query=request_data.document or request_data.query,
root_value=root_value,
variable_values=request_data.variables,
context_value=context,
operation_name=request_data.operation_name,
allowed_operation_types=allowed_operation_types,
operation_extensions=request_data.extensions,
)
def parse_multipart(self, request: SyncHTTPRequestAdapter) -> dict[str, str]:
operations = self.parse_json(request.post_data.get("operations", "{}"))
files_map = self.parse_json(request.post_data.get("map", "{}"))
try:
return replace_placeholders_with_files(operations, files_map, request.files)
except KeyError as e:
raise HTTPException(400, "File(s) missing in form data") from e
def get_graphql_request_data(
self,
request: SyncHTTPRequestAdapter,
context: Context,
data: dict[str, Any],
protocol: Literal["http", "http-strict", "multipart-subscription"],
) -> GraphQLRequestData:
return GraphQLRequestData(
query=data.get("query"),
document=None,
variables=data.get("variables"),
operation_name=data.get("operationName"),
extensions=data.get("extensions"),
protocol=protocol,
)
def parse_http_body(
self,
request: SyncHTTPRequestAdapter,
context: Context,
) -> GraphQLRequestData:
accept_type = request.headers.get("accept", "") or request.headers.get(
"http-accept", ""
)
content_type, params = parse_content_type(request.content_type or "")
protocol = "http"
if "application/graphql-response+json" in accept_type:
protocol = "http-strict"
if request.method == "GET":
data = self.parse_query_params(request.query_params)
elif "application/json" in content_type:
data = self.parse_json(request.body)
# TODO: multipart via get?
elif self.multipart_uploads_enabled and content_type == "multipart/form-data":
data = self.parse_multipart(request)
elif self._is_multipart_subscriptions(content_type, params):
raise HTTPException(
400, "Multipart subscriptions are not supported in sync mode"
)
else:
raise HTTPException(400, "Unsupported content type")
return self.get_graphql_request_data(request, context, data, protocol)
def _handle_errors(
self, errors: list[GraphQLError], response_data: GraphQLHTTPResponse
) -> None:
"""Hook to allow custom handling of errors, used by the Sentry Integration."""
def run(
self,
request: Request,
context: Context = UNSET,
root_value: Optional[RootValue] = UNSET,
) -> Response:
request_adapter = self.request_adapter_class(request)
if request_adapter.method == "OPTIONS":
# We are in a CORS preflight request, we can return a 200 OK by default
# as further checks will need to be done by the middleware
raise HTTPException(200, "")
if not self.is_request_allowed(request_adapter):
raise HTTPException(405, "GraphQL only supports GET and POST requests.")
sub_response = self.get_sub_response(request)
context = (
self.get_context(request, response=sub_response)
if context is UNSET
else context
)
try:
request_data = self.parse_http_body(request_adapter, context)
except json.decoder.JSONDecodeError as e:
raise HTTPException(400, "Unable to parse request body as JSON") from e
# DO this only when doing files
except KeyError as e:
raise HTTPException(400, "File(s) missing in form data") from e
if request_data.variables is not None and not isinstance(
request_data.variables, dict
):
raise HTTPException(400, "Variables must be a JSON object")
if request_data.extensions is not None and not isinstance(
request_data.extensions, dict
):
raise HTTPException(400, "Extensions must be a JSON object")
allowed_operation_types = operation_type_from_http(request_adapter.method)
if request_adapter.method == "GET":
if not self.allow_queries_via_get:
allowed_operation_types = allowed_operation_types - {
OperationType.QUERY
}
if self.graphql_ide and self.should_render_graphql_ide(request_adapter):
return self.render_graphql_ide(request, request_data)
root_value = self.get_root_value(request) if root_value is UNSET else root_value
is_strict = request_data.protocol == "http-strict"
try:
result = self.execute_operation(
request_adapter=request_adapter,
request_data=request_data,
context=context,
root_value=root_value,
allowed_operation_types=allowed_operation_types,
)
except HTTPException:
raise
except GraphQLValidationError as e:
if is_strict:
sub_response.status_code = 400 # type: ignore
result = ExecutionResult(data=None, errors=e.errors)
except InvalidOperationTypeError as e:
raise HTTPException(
400, e.as_http_error_reason(request_adapter.method)
) from e
except Exception as e:
raise HTTPException(400, str(e)) from e
response_data = self.process_result(
request=request, result=result, strict=is_strict
)
if result.errors:
self._handle_errors(result.errors, response_data)
return self.create_response(
response_data=response_data, sub_response=sub_response, is_strict=is_strict
)
def process_result(
self, request: Request, result: ExecutionResult, strict: bool = False
) -> GraphQLHTTPResponse:
return process_result(result, strict)
__all__ = ["SyncBaseHTTPView"]