strawberry-graphql 0.237.3__py3-none-any.whl → 0.238.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,6 +15,7 @@ from typing import (
15
15
  )
16
16
 
17
17
  from aiohttp import web
18
+ from aiohttp.multipart import BodyPartReader
18
19
  from strawberry.aiohttp.handlers import (
19
20
  GraphQLTransportWSHandler,
20
21
  GraphQLWSHandler,
@@ -60,6 +61,7 @@ class AioHTTPRequestAdapter(AsyncHTTPRequestAdapter):
60
61
  files: Dict[str, Any] = {}
61
62
 
62
63
  async for field in reader:
64
+ assert isinstance(field, BodyPartReader)
63
65
  assert field.name
64
66
 
65
67
  if field.filename:
@@ -24,7 +24,7 @@ class SentryTracingExtension(SchemaExtension):
24
24
  execution_context: Optional[ExecutionContext] = None,
25
25
  ) -> None:
26
26
  warnings.warn(
27
- "The Sentry tracing extension is deprecated, please update to sentry>=1.32.0",
27
+ "The Sentry tracing extension is deprecated, please update to sentry-sdk>=1.32.0",
28
28
  DeprecationWarning,
29
29
  stacklevel=2,
30
30
  )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: strawberry-graphql
3
- Version: 0.237.3
3
+ Version: 0.238.0
4
4
  Summary: A library for creating GraphQL APIs
5
5
  Home-page: https://strawberry.rocks/
6
6
  License: MIT
@@ -35,7 +35,6 @@ Provides-Extra: pydantic
35
35
  Provides-Extra: pyinstrument
36
36
  Provides-Extra: quart
37
37
  Provides-Extra: sanic
38
- Provides-Extra: starlite
39
38
  Requires-Dist: Django (>=3.2) ; extra == "django"
40
39
  Requires-Dist: aiohttp (>=3.7.4.post0,<4.0.0) ; extra == "aiohttp"
41
40
  Requires-Dist: asgiref (>=3.2,<4.0) ; extra == "django" or extra == "channels"
@@ -59,7 +58,6 @@ Requires-Dist: quart (>=0.19.3) ; extra == "quart"
59
58
  Requires-Dist: rich (>=12.0.0) ; extra == "debug" or extra == "debug-server" or extra == "cli"
60
59
  Requires-Dist: sanic (>=20.12.2) ; extra == "sanic"
61
60
  Requires-Dist: starlette (>=0.18.0) ; extra == "asgi" or extra == "debug-server"
62
- Requires-Dist: starlite (>=1.48.0) ; (python_version >= "3.8") and (extra == "starlite")
63
61
  Requires-Dist: typer (>=0.7.0) ; extra == "debug-server" or extra == "cli"
64
62
  Requires-Dist: typing-extensions (>=4.5.0)
65
63
  Requires-Dist: uvicorn (>=0.11.6) ; extra == "debug-server"
@@ -6,7 +6,7 @@ strawberry/aiohttp/handlers/graphql_transport_ws_handler.py,sha256=-dihpF3pueV6j
6
6
  strawberry/aiohttp/handlers/graphql_ws_handler.py,sha256=Ol8tBLIeal7bRiG_uxyJXnXo24xMDEh6M5XsuCyUpVQ,2275
7
7
  strawberry/aiohttp/test/__init__.py,sha256=4xxdUZtIISSOwjrcnmox7AvT4WWjowCm5bUuPdQneMg,71
8
8
  strawberry/aiohttp/test/client.py,sha256=4vjTDxtNVfpa74GfUUO7efPI6Ssh1vzfCYp3tPA-SLk,1357
9
- strawberry/aiohttp/views.py,sha256=3Imc-kP01zhDYmWQRFcQyZsObqdELQ84d-3zFrpHNxA,6091
9
+ strawberry/aiohttp/views.py,sha256=q1y0zCuLNlwD_o4aosm7dNc-2F-ZJY95kiq1Ip0Prmw,6189
10
10
  strawberry/annotation.py,sha256=ftSxGZQUk4C5_5YRM_wNJFVVnZi0XOp71kD7zv4oxbU,13077
11
11
  strawberry/asgi/__init__.py,sha256=37w7FeDEmfq2YXKeyyBgjTAliz9ut5Y0-0dVgfE-PAk,6973
12
12
  strawberry/asgi/handlers/__init__.py,sha256=rz5Gth2eJUn7tDq2--99KSNFeMdDPpLFCkfA7vge0cI,235
@@ -114,7 +114,7 @@ strawberry/extensions/tracing/__init__.py,sha256=wx8_EAroGhNrP4HiGYMgKo8jnCsfde5
114
114
  strawberry/extensions/tracing/apollo.py,sha256=XlI88NzSZBSmBHEJ9iitDU9br2-9CdjdtHE_eiTJCIw,5880
115
115
  strawberry/extensions/tracing/datadog.py,sha256=khxvY4_WTjYaeJUb_dn6mLvmk9TCS4tIodnC3G-9pTo,5541
116
116
  strawberry/extensions/tracing/opentelemetry.py,sha256=MH2j71denfLmzInl6zcTzxzckqjcwOzm_F305z8-vYw,7281
117
- strawberry/extensions/tracing/sentry.py,sha256=y4km7GypJelFnlZbJ4L8aUR665T3sTIp4oauczA-uvE,5023
117
+ strawberry/extensions/tracing/sentry.py,sha256=r_U1OeiDDq-Mf6v30-aEuHhrio2Pckxfrcrdu_OAnWM,5027
118
118
  strawberry/extensions/tracing/utils.py,sha256=tXZNyqfct6YNSWi3GRj4GU1fKQGvSce8ZESfoVeys7U,654
119
119
  strawberry/extensions/utils.py,sha256=YPiacKNLQXvpYj-HI6fR5ORFdM9RrcdabGeM7F8vBGg,1001
120
120
  strawberry/extensions/validation_cache.py,sha256=CZ-brPYA1grL_lW38Rq4TxEVKlHM2n1DC6q9BHlSF4g,1398
@@ -194,11 +194,6 @@ strawberry/schema/validation_rules/one_of.py,sha256=fPuYzCyLT7p9y7dHF_sWTImArTQa
194
194
  strawberry/schema_codegen/__init__.py,sha256=mhOfvC-h6ksmckXE2TC8WWlMgayNa2xwlbNelqFpeVY,24399
195
195
  strawberry/schema_directive.py,sha256=xFHoKOAWgVzDWt_N0ZdON3DBRByJkvMHt5TIvFLjUUU,2005
196
196
  strawberry/schema_directives.py,sha256=KGKFWCODjm1Ah9qNV_bBwbic7Mld4qLWnWQkev-PG8A,175
197
- strawberry/starlite/__init__.py,sha256=v209swT8H9MljVL-npvANhEO1zz3__PSfxb_Ix-NoeE,134
198
- strawberry/starlite/controller.py,sha256=ckZGcttZ-Ok30MSxtIiZO3wigJTw-it58s3kfHqua-s,12231
199
- strawberry/starlite/handlers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
200
- strawberry/starlite/handlers/graphql_transport_ws_handler.py,sha256=k6kr8oTX5DGVpDHZkSotvYIcqKpyXO2qDr1RbKyiwXM,2023
201
- strawberry/starlite/handlers/graphql_ws_handler.py,sha256=BJtwhuIwaKfp8rGbvCBPKaDn_d2VY7Qd1iWdJhxHNK4,2256
202
197
  strawberry/static/apollo-sandbox.html,sha256=2XzkbE0dqsFHqehE-jul9_J9TFOpwA6Ylrlo0Kdx_9w,973
203
198
  strawberry/static/graphiql.html,sha256=r1JCF4vpptjISOAHaCrgck2b3qf0oaCEzljECWQ7aCE,4380
204
199
  strawberry/static/pathfinder.html,sha256=0DPx9AmJ2C_sJstFXnWOz9k5tVQHeHaK7qdVY4lAlmk,1547
@@ -248,8 +243,8 @@ strawberry/utils/logging.py,sha256=U1cseHGquN09YFhFmRkiphfASKCyK0HUZREImPgVb0c,7
248
243
  strawberry/utils/operation.py,sha256=SSXxN-vMqdHO6W2OZtip-1z7y4_A-eTVFdhDvhKeLCk,1193
249
244
  strawberry/utils/str_converters.py,sha256=KGd7QH90RevaJjH6SQEkiVVsb8KuhJr_wv5AsI7UzQk,897
250
245
  strawberry/utils/typing.py,sha256=tUHHX2YTGX417EEQHB6j0B8-p-fg31ZI8csc9SUoq2I,14260
251
- strawberry_graphql-0.237.3.dist-info/LICENSE,sha256=m-XnIVUKqlG_AWnfi9NReh9JfKhYOB-gJfKE45WM1W8,1072
252
- strawberry_graphql-0.237.3.dist-info/METADATA,sha256=sWyrEwqkg62uUtYwDNAq18skuwzvCaVZQnsLLCNeSKc,7821
253
- strawberry_graphql-0.237.3.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
254
- strawberry_graphql-0.237.3.dist-info/entry_points.txt,sha256=Nk7-aT3_uEwCgyqtHESV9H6Mc31cK-VAvhnQNTzTb4k,49
255
- strawberry_graphql-0.237.3.dist-info/RECORD,,
246
+ strawberry_graphql-0.238.0.dist-info/LICENSE,sha256=m-XnIVUKqlG_AWnfi9NReh9JfKhYOB-gJfKE45WM1W8,1072
247
+ strawberry_graphql-0.238.0.dist-info/METADATA,sha256=QyzfeHo1tGJ5zaJ3w5B7DcdL_4P1XXgZWNDjxyrnUYU,7707
248
+ strawberry_graphql-0.238.0.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
249
+ strawberry_graphql-0.238.0.dist-info/entry_points.txt,sha256=Nk7-aT3_uEwCgyqtHESV9H6Mc31cK-VAvhnQNTzTb4k,49
250
+ strawberry_graphql-0.238.0.dist-info/RECORD,,
@@ -1,3 +0,0 @@
1
- from strawberry.starlite.controller import BaseContext, make_graphql_controller
2
-
3
- __all__ = ["BaseContext", "make_graphql_controller"]
@@ -1,387 +0,0 @@
1
- """Starlite integration for strawberry-graphql."""
2
-
3
- from __future__ import annotations
4
-
5
- import warnings
6
- from dataclasses import dataclass
7
- from datetime import timedelta
8
- from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Tuple, Union, cast
9
- from typing_extensions import deprecated
10
-
11
- from starlite import (
12
- BackgroundTasks,
13
- Controller,
14
- MediaType,
15
- Provide,
16
- Request,
17
- Response,
18
- WebSocket,
19
- get,
20
- post,
21
- websocket,
22
- )
23
- from starlite.exceptions import (
24
- NotFoundException,
25
- ValidationException,
26
- )
27
- from starlite.status_codes import HTTP_200_OK
28
- from strawberry.exceptions import InvalidCustomContext
29
- from strawberry.http.async_base_view import AsyncBaseHTTPView, AsyncHTTPRequestAdapter
30
- from strawberry.http.exceptions import HTTPException
31
- from strawberry.http.types import FormData, HTTPMethod, QueryParams
32
- from strawberry.http.typevars import (
33
- Context,
34
- RootValue,
35
- )
36
- from strawberry.subscriptions import GRAPHQL_TRANSPORT_WS_PROTOCOL, GRAPHQL_WS_PROTOCOL
37
- from strawberry.subscriptions.protocols.graphql_transport_ws import (
38
- WS_4406_PROTOCOL_NOT_ACCEPTABLE,
39
- )
40
-
41
- from .handlers.graphql_transport_ws_handler import (
42
- GraphQLTransportWSHandler as BaseGraphQLTransportWSHandler,
43
- )
44
- from .handlers.graphql_ws_handler import GraphQLWSHandler as BaseGraphQLWSHandler
45
-
46
- if TYPE_CHECKING:
47
- from typing import FrozenSet, List, Type
48
-
49
- from starlite.types import AnyCallable, Dependencies
50
- from strawberry.http import GraphQLHTTPResponse
51
- from strawberry.http.ides import GraphQL_IDE
52
- from strawberry.schema import BaseSchema
53
-
54
- MergedContext = Union[
55
- "BaseContext",
56
- Union[
57
- Dict[str, Any],
58
- Dict[str, BackgroundTasks],
59
- Dict[str, Request[Any, Any]],
60
- Dict[str, Response[Any]],
61
- Dict[str, websocket],
62
- ],
63
- ]
64
-
65
- CustomContext = Union["BaseContext", Dict[str, Any]]
66
-
67
-
68
- async def _context_getter(
69
- custom_context: Optional[CustomContext],
70
- request: Request[Any, Any],
71
- response: Response[Any],
72
- ) -> MergedContext:
73
- if isinstance(custom_context, BaseContext):
74
- custom_context.request = request
75
- return custom_context
76
-
77
- default_context = {
78
- "request": request,
79
- "response": response,
80
- }
81
-
82
- if isinstance(custom_context, dict):
83
- return {
84
- **default_context,
85
- **custom_context,
86
- }
87
-
88
- if custom_context is None:
89
- return default_context
90
-
91
- raise InvalidCustomContext()
92
-
93
-
94
- @dataclass
95
- class GraphQLResource:
96
- data: Optional[Dict[str, object]]
97
- errors: Optional[List[object]]
98
- extensions: Optional[Dict[str, object]]
99
-
100
-
101
- @dataclass
102
- class EmptyResponseModel:
103
- pass
104
-
105
-
106
- class GraphQLWSHandler(BaseGraphQLWSHandler):
107
- async def get_context(self) -> Any:
108
- return await self._get_context()
109
-
110
- async def get_root_value(self) -> Any:
111
- return await self._get_root_value()
112
-
113
-
114
- class GraphQLTransportWSHandler(BaseGraphQLTransportWSHandler):
115
- async def get_context(self) -> Any:
116
- return await self._get_context()
117
-
118
- async def get_root_value(self) -> Any:
119
- return await self._get_root_value()
120
-
121
-
122
- @deprecated(
123
- "The `starlite` integration is deprecated in favor of `litestar` integration",
124
- stacklevel=2,
125
- )
126
- class StarliteRequestAdapter(AsyncHTTPRequestAdapter):
127
- def __init__(self, request: Request[Any, Any]) -> None:
128
- self.request = request
129
-
130
- @property
131
- def query_params(self) -> QueryParams:
132
- return self.request.query_params
133
-
134
- @property
135
- def method(self) -> HTTPMethod:
136
- return cast(HTTPMethod, self.request.method.upper())
137
-
138
- @property
139
- def headers(self) -> Mapping[str, str]:
140
- return self.request.headers
141
-
142
- @property
143
- def content_type(self) -> Optional[str]:
144
- return self.request.content_type[0]
145
-
146
- async def get_body(self) -> bytes:
147
- return await self.request.body()
148
-
149
- async def get_form_data(self) -> FormData:
150
- multipart_data = await self.request.form()
151
-
152
- return FormData(form=multipart_data, files=multipart_data)
153
-
154
-
155
- class BaseContext:
156
- def __init__(self) -> None:
157
- self.request: Optional[Union[Request, WebSocket]] = None
158
- self.response: Optional[Response] = None
159
-
160
-
161
- @deprecated(
162
- "The `starlite` integration is deprecated in favor of `litestar` integration",
163
- stacklevel=2,
164
- )
165
- def make_graphql_controller(
166
- schema: BaseSchema,
167
- path: str = "",
168
- graphiql: Optional[bool] = None,
169
- graphql_ide: Optional[GraphQL_IDE] = "graphiql",
170
- allow_queries_via_get: bool = True,
171
- keep_alive: bool = False,
172
- keep_alive_interval: float = 1,
173
- debug: bool = False,
174
- # TODO: root typevar
175
- root_value_getter: Optional[AnyCallable] = None,
176
- # TODO: context typevar
177
- context_getter: Optional[AnyCallable] = None,
178
- subscription_protocols: Tuple[str, ...] = (
179
- GRAPHQL_TRANSPORT_WS_PROTOCOL,
180
- GRAPHQL_WS_PROTOCOL,
181
- ),
182
- connection_init_wait_timeout: timedelta = timedelta(minutes=1),
183
- ) -> Type[Controller]:
184
- routes_path = path
185
-
186
- if context_getter is None:
187
-
188
- def custom_context_getter_() -> None:
189
- return None
190
-
191
- else:
192
- custom_context_getter_ = context_getter
193
-
194
- if root_value_getter is None:
195
-
196
- def root_value_getter_() -> None:
197
- return None
198
-
199
- else:
200
- root_value_getter_ = root_value_getter
201
-
202
- def response_getter() -> Response[Any]:
203
- return Response({}, background=BackgroundTasks([]))
204
-
205
- schema_ = schema
206
- allow_queries_via_get_ = allow_queries_via_get
207
- graphql_ide_: Optional[GraphQL_IDE]
208
-
209
- if graphiql is not None:
210
- warnings.warn(
211
- "The `graphiql` argument is deprecated in favor of `graphql_ide`",
212
- DeprecationWarning,
213
- stacklevel=2,
214
- )
215
- graphql_ide_ = "graphiql" if graphiql else None
216
- else:
217
- graphql_ide_ = graphql_ide
218
-
219
- class GraphQLController(
220
- Controller,
221
- AsyncBaseHTTPView[
222
- Request[Any, Any], Response[Any], Response[Any], Context, RootValue
223
- ],
224
- ):
225
- request_adapter_class = StarliteRequestAdapter
226
- path: str = routes_path
227
- dependencies: Optional[Dependencies] = {
228
- "custom_context": Provide(custom_context_getter_),
229
- "context": Provide(_context_getter),
230
- "root_value": Provide(root_value_getter_),
231
- "response": Provide(response_getter),
232
- }
233
- graphql_ws_handler_class: Type[GraphQLWSHandler] = GraphQLWSHandler
234
- graphql_transport_ws_handler_class: Type[GraphQLTransportWSHandler] = (
235
- GraphQLTransportWSHandler
236
- )
237
-
238
- _keep_alive: bool = keep_alive
239
- _keep_alive_interval: float = keep_alive_interval
240
- _debug: bool = debug
241
- _protocols: Tuple[str, ...] = subscription_protocols
242
- _connection_init_wait_timeout: timedelta = connection_init_wait_timeout
243
- _graphiql_allowed_accept: FrozenSet[str] = frozenset({"text/html", "*/*"})
244
-
245
- schema: BaseSchema = schema_
246
- allow_queries_via_get = allow_queries_via_get_
247
- graphql_ide = graphql_ide_
248
-
249
- async def execute_request(
250
- self,
251
- request: Request[Any, Any],
252
- context: CustomContext,
253
- root_value: Any,
254
- ) -> Response[Union[GraphQLResource, str]]:
255
- try:
256
- return await self.run(
257
- request,
258
- # TODO: check the dependency, above, can we make it so that
259
- # we don't need to type ignore here?
260
- context=context, # type: ignore
261
- root_value=root_value,
262
- )
263
- except HTTPException as e:
264
- return Response(
265
- e.reason,
266
- status_code=e.status_code,
267
- media_type=MediaType.TEXT,
268
- )
269
-
270
- async def render_graphql_ide(self, request: Request[Any, Any]) -> Response[str]:
271
- return Response(self.graphql_ide_html, media_type=MediaType.HTML)
272
-
273
- def create_response(
274
- self, response_data: GraphQLHTTPResponse, sub_response: Response[bytes]
275
- ) -> Response[bytes]:
276
- response = Response(
277
- self.encode_json(response_data).encode(),
278
- status_code=HTTP_200_OK,
279
- media_type=MediaType.JSON,
280
- )
281
-
282
- response.headers.update(sub_response.headers)
283
- response.cookies.extend(sub_response.cookies)
284
- response.background = sub_response.background
285
-
286
- if sub_response.status_code:
287
- response.status_code = sub_response.status_code
288
-
289
- return response
290
-
291
- @get(raises=[ValidationException, NotFoundException])
292
- async def handle_http_get(
293
- self,
294
- request: Request[Any, Any],
295
- context: CustomContext,
296
- root_value: Any,
297
- response: Response[Any],
298
- ) -> Response[Union[GraphQLResource, str]]:
299
- self.temporal_response = response
300
-
301
- return await self.execute_request(
302
- request=request,
303
- context=context,
304
- root_value=root_value,
305
- )
306
-
307
- @post(status_code=HTTP_200_OK)
308
- async def handle_http_post(
309
- self,
310
- request: Request[Any, Any],
311
- context: CustomContext,
312
- root_value: Any,
313
- response: Response[Any],
314
- ) -> Response[Union[GraphQLResource, str]]:
315
- self.temporal_response = response
316
-
317
- return await self.execute_request(
318
- request=request,
319
- context=context,
320
- root_value=root_value,
321
- )
322
-
323
- async def get_context(
324
- self, request: Request[Any, Any], response: Response[Any]
325
- ) -> Context: # pragma: no cover
326
- raise ValueError("`get_context` is not used by Starlite's controller")
327
-
328
- async def get_root_value(
329
- self, request: Request[Any, Any]
330
- ) -> Optional[RootValue]: # pragma: no cover
331
- raise ValueError("`get_root_value` is not used by Starlite's controller")
332
-
333
- async def get_sub_response(self, request: Request[Any, Any]) -> Response[Any]:
334
- return self.temporal_response
335
-
336
- @websocket()
337
- async def websocket_endpoint(
338
- self,
339
- socket: WebSocket,
340
- context: CustomContext,
341
- root_value: Any,
342
- ) -> None:
343
- async def _get_context() -> CustomContext:
344
- return context
345
-
346
- async def _get_root_value() -> Any:
347
- return root_value
348
-
349
- preferred_protocol = self.pick_preferred_protocol(socket)
350
- if preferred_protocol == GRAPHQL_TRANSPORT_WS_PROTOCOL:
351
- await self.graphql_transport_ws_handler_class(
352
- schema=self.schema,
353
- debug=self._debug,
354
- connection_init_wait_timeout=self._connection_init_wait_timeout,
355
- get_context=_get_context,
356
- get_root_value=_get_root_value,
357
- ws=socket,
358
- ).handle()
359
- elif preferred_protocol == GRAPHQL_WS_PROTOCOL:
360
- await self.graphql_ws_handler_class(
361
- schema=self.schema,
362
- debug=self._debug,
363
- keep_alive=self._keep_alive,
364
- keep_alive_interval=self._keep_alive_interval,
365
- get_context=_get_context,
366
- get_root_value=_get_root_value,
367
- ws=socket,
368
- ).handle()
369
- else:
370
- await socket.close(code=WS_4406_PROTOCOL_NOT_ACCEPTABLE)
371
-
372
- def pick_preferred_protocol(self, socket: WebSocket) -> Optional[str]:
373
- protocols: List[str] = socket.scope["subprotocols"]
374
- intersection = set(protocols) & set(self._protocols)
375
- return (
376
- min(
377
- intersection,
378
- key=lambda i: protocols.index(i) if i else "",
379
- default=None,
380
- )
381
- or None
382
- )
383
-
384
- return GraphQLController
385
-
386
-
387
- __all__ = ["make_graphql_controller"]
File without changes
@@ -1,59 +0,0 @@
1
- from datetime import timedelta
2
- from typing import Any, Callable
3
-
4
- from starlite import WebSocket
5
- from starlite.exceptions import SerializationException, WebSocketDisconnect
6
- from strawberry.schema import BaseSchema
7
- from strawberry.subscriptions import GRAPHQL_TRANSPORT_WS_PROTOCOL
8
- from strawberry.subscriptions.protocols.graphql_transport_ws.handlers import (
9
- BaseGraphQLTransportWSHandler,
10
- )
11
-
12
-
13
- class GraphQLTransportWSHandler(BaseGraphQLTransportWSHandler):
14
- def __init__(
15
- self,
16
- schema: BaseSchema,
17
- debug: bool,
18
- connection_init_wait_timeout: timedelta,
19
- get_context: Callable,
20
- get_root_value: Callable,
21
- ws: WebSocket,
22
- ) -> None:
23
- super().__init__(schema, debug, connection_init_wait_timeout)
24
- self._get_context = get_context
25
- self._get_root_value = get_root_value
26
- self._ws = ws
27
-
28
- async def get_context(self) -> Any:
29
- return await self._get_context()
30
-
31
- async def get_root_value(self) -> Any:
32
- return await self._get_root_value()
33
-
34
- async def send_json(self, data: dict) -> None:
35
- await self._ws.send_json(data)
36
-
37
- async def close(self, code: int, reason: str) -> None:
38
- await self._ws.close(code=code, reason=reason)
39
-
40
- async def handle_request(self) -> None:
41
- await self._ws.accept(subprotocols=GRAPHQL_TRANSPORT_WS_PROTOCOL)
42
- self.on_request_accepted()
43
-
44
- try:
45
- while self._ws.connection_state != "disconnect":
46
- try:
47
- message = await self._ws.receive_json()
48
- except (SerializationException, ValueError): # noqa: PERF203
49
- error_message = "WebSocket message type must be text"
50
- await self.handle_invalid_message(error_message)
51
- else:
52
- await self.handle_message(message)
53
- except WebSocketDisconnect: # pragma: no cover
54
- pass
55
- finally:
56
- await self.shutdown()
57
-
58
-
59
- __all__ = ["GraphQLTransportWSHandler"]
@@ -1,64 +0,0 @@
1
- from contextlib import suppress
2
- from typing import Any, Callable, Optional
3
-
4
- from starlite import WebSocket
5
- from starlite.exceptions import SerializationException, WebSocketDisconnect
6
- from strawberry.schema import BaseSchema
7
- from strawberry.subscriptions import GRAPHQL_WS_PROTOCOL
8
- from strawberry.subscriptions.protocols.graphql_ws.handlers import BaseGraphQLWSHandler
9
- from strawberry.subscriptions.protocols.graphql_ws.types import OperationMessage
10
-
11
-
12
- class GraphQLWSHandler(BaseGraphQLWSHandler):
13
- def __init__(
14
- self,
15
- schema: BaseSchema,
16
- debug: bool,
17
- keep_alive: bool,
18
- keep_alive_interval: float,
19
- get_context: Callable,
20
- get_root_value: Callable,
21
- ws: WebSocket,
22
- ) -> None:
23
- super().__init__(schema, debug, keep_alive, keep_alive_interval)
24
- self._get_context = get_context
25
- self._get_root_value = get_root_value
26
- self._ws = ws
27
-
28
- async def get_context(self) -> Any:
29
- return await self._get_context()
30
-
31
- async def get_root_value(self) -> Any:
32
- return await self._get_root_value()
33
-
34
- async def send_json(self, data: OperationMessage) -> None:
35
- await self._ws.send_json(data)
36
-
37
- async def close(self, code: int = 1000, reason: Optional[str] = None) -> None:
38
- await self._ws.close(code=code, reason=reason)
39
-
40
- async def handle_request(self) -> Any:
41
- await self._ws.accept(subprotocols=GRAPHQL_WS_PROTOCOL)
42
-
43
- try:
44
- while self._ws.connection_state != "disconnect":
45
- try:
46
- message = await self._ws.receive_json()
47
- except (SerializationException, ValueError): # noqa: PERF203
48
- # Ignore non-text messages
49
- continue
50
- else:
51
- await self.handle_message(message)
52
- except WebSocketDisconnect: # pragma: no cover
53
- pass
54
- finally:
55
- if self.keep_alive_task:
56
- self.keep_alive_task.cancel()
57
- with suppress(BaseException):
58
- await self.keep_alive_task
59
-
60
- for operation_id in list(self.subscriptions.keys()):
61
- await self.cleanup_operation(operation_id)
62
-
63
-
64
- __all__ = ["GraphQLWSHandler"]