-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathviews.py
More file actions
225 lines (179 loc) · 6.62 KB
/
views.py
File metadata and controls
225 lines (179 loc) · 6.62 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
from __future__ import annotations
import warnings
from typing import (
TYPE_CHECKING,
Any,
ClassVar,
Optional,
Union,
cast,
)
from typing_extensions import TypeGuard
from flask import Request, Response, request
from flask.views import View
from graphql_server.http import GraphQLRequestData
from graphql_server.http.async_base_view import (
AsyncBaseHTTPView,
AsyncHTTPRequestAdapter,
)
from graphql_server.http.exceptions import HTTPException
from graphql_server.http.sync_base_view import (
SyncBaseHTTPView,
SyncHTTPRequestAdapter,
)
from graphql_server.http.types import FormData, HTTPMethod, QueryParams
from graphql_server.http.typevars import Context, RootValue
if TYPE_CHECKING:
from collections.abc import Mapping
from graphql.type import GraphQLSchema
from flask.typing import ResponseReturnValue
from graphql_server.http import GraphQLHTTPResponse
from graphql_server.http.ides import GraphQL_IDE
class FlaskHTTPRequestAdapter(SyncHTTPRequestAdapter):
def __init__(self, request: Request) -> None:
self.request = request
@property
def query_params(self) -> QueryParams:
return self.request.args.to_dict()
@property
def body(self) -> Union[str, bytes]:
return self.request.data.decode()
@property
def method(self) -> HTTPMethod:
return cast("HTTPMethod", self.request.method.upper())
@property
def headers(self) -> Mapping[str, str]:
return self.request.headers # type: ignore
@property
def post_data(self) -> Mapping[str, Union[str, bytes]]:
return self.request.form
@property
def files(self) -> Mapping[str, Any]:
return self.request.files
@property
def content_type(self) -> Optional[str]:
return self.request.content_type
class BaseGraphQLView:
graphql_ide: Optional[GraphQL_IDE]
def __init__(
self,
schema: GraphQLSchema,
graphiql: Optional[bool] = None,
graphql_ide: Optional[GraphQL_IDE] = "graphiql",
allow_queries_via_get: bool = True,
multipart_uploads_enabled: bool = False,
) -> None:
self.schema = schema
self.graphiql = graphiql
self.allow_queries_via_get = allow_queries_via_get
self.multipart_uploads_enabled = multipart_uploads_enabled
if graphiql is not None:
warnings.warn(
"The `graphiql` argument is deprecated in favor of `graphql_ide`",
DeprecationWarning,
stacklevel=2,
)
self.graphql_ide = "graphiql" if graphiql else None
else:
self.graphql_ide = graphql_ide
def create_response(
self,
response_data: GraphQLHTTPResponse,
sub_response: Response,
is_strict: bool,
) -> Response:
sub_response.set_data(self.encode_json(response_data)) # type: ignore
sub_response.headers["content-type"] = (
"application/graphql-response+json" if is_strict else "application/json"
)
return sub_response
class GraphQLView(
BaseGraphQLView,
SyncBaseHTTPView[Request, Response, Response, Context, RootValue],
View,
):
methods: ClassVar[list[str]] = ["GET", "POST"]
allow_queries_via_get: bool = True
request_adapter_class = FlaskHTTPRequestAdapter
def get_context(self, request: Request, response: Response) -> Context:
return {"request": request, "response": response} # type: ignore
def get_root_value(self, request: Request) -> Optional[RootValue]:
return None
def get_sub_response(self, request: Request) -> Response:
return Response(status=200, content_type="application/json")
def dispatch_request(self) -> ResponseReturnValue:
try:
return self.run(request=request)
except HTTPException as e:
return Response(
response=e.reason,
status=e.status_code,
)
def render_graphql_ide(
self, request: Request, request_data: GraphQLRequestData
) -> Response:
content = request_data.to_template_string(self.graphql_ide_html)
return Response(content, status=200, content_type="text/html")
class AsyncFlaskHTTPRequestAdapter(AsyncHTTPRequestAdapter):
def __init__(self, request: Request) -> None:
self.request = request
@property
def query_params(self) -> QueryParams:
return self.request.args.to_dict()
@property
def method(self) -> HTTPMethod:
return cast("HTTPMethod", self.request.method.upper())
@property
def content_type(self) -> Optional[str]:
return self.request.content_type
@property
def headers(self) -> Mapping[str, str]:
return self.request.headers # type: ignore
async def get_body(self) -> str:
return self.request.data.decode()
async def get_form_data(self) -> FormData:
return FormData(
files=self.request.files,
form=self.request.form,
)
class AsyncGraphQLView(
BaseGraphQLView,
AsyncBaseHTTPView[
Request, Response, Response, Request, Response, Context, RootValue
],
View,
):
methods: ClassVar[list[str]] = ["GET", "POST"]
allow_queries_via_get: bool = True
request_adapter_class = AsyncFlaskHTTPRequestAdapter
async def get_context(self, request: Request, response: Response) -> Context:
return {"request": request, "response": response} # type: ignore
async def get_root_value(self, request: Request) -> Optional[RootValue]:
return None
async def get_sub_response(self, request: Request) -> Response:
return Response(status=200, content_type="application/json")
async def dispatch_request(self) -> ResponseReturnValue: # type: ignore
try:
return await self.run(request=request)
except HTTPException as e:
return Response(
response=e.reason,
status=e.status_code,
)
async def render_graphql_ide(
self, request: Request, request_data: GraphQLRequestData
) -> Response:
content = request_data.to_template_string(self.graphql_ide_html)
return Response(content, status=200, content_type="text/html")
def is_websocket_request(self, request: Request) -> TypeGuard[Request]:
return False
async def pick_websocket_subprotocol(self, request: Request) -> Optional[str]:
raise NotImplementedError
async def create_websocket_response(
self, request: Request, subprotocol: Optional[str]
) -> Response:
raise NotImplementedError
__all__ = [
"AsyncGraphQLView",
"GraphQLView",
]