Skip to content

Commit 9db69f8

Browse files
author
Andrey Zelenchuk
committed
Introduce per-operation contexts.
1 parent c11398c commit 9db69f8

File tree

3 files changed

+36
-3
lines changed

3 files changed

+36
-3
lines changed

channels_graphql_ws/graphql_ws_consumer.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@
5858
import promise
5959
import rx
6060

61-
from .scope_as_context import ScopeAsContext
61+
from .operation_context import OperationContext
6262
from .serializer import Serializer
6363

6464
# Module logger.
@@ -550,7 +550,7 @@ async def _on_gql_start(self, operation_id, payload):
550550

551551
# Create object-like context (like in `Query` or `Mutation`)
552552
# from the dict-like one provided by the Channels.
553-
context = ScopeAsContext(self.scope)
553+
context = OperationContext(self.scope)
554554

555555
# Adding channel name to the context because it seems to be
556556
# useful for some use cases, take a loot at the issue from
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
"""Just `OperationContext` class."""
2+
3+
from channels_graphql_ws.scope_as_context import ScopeAsContext
4+
5+
6+
class OperationContext(ScopeAsContext):
7+
"""
8+
The context intended to use in methods of Graphene classes as `info.context`.
9+
10+
This class provides two public properties:
11+
1. `scope` - per-connection context. This is the `scope` of Django Channels.
12+
2. `operation_context` - per-operation context. Empty. Fill free to store your's
13+
data here.
14+
15+
For backward compatibility:
16+
- Method `_asdict` returns the `scope`.
17+
- Other attributes are routed to the `scope`.
18+
"""
19+
20+
def __init__(self, scope: dict):
21+
"""Nothing interesting here."""
22+
super().__init__(scope)
23+
self._operation_context: dict = {}
24+
25+
@property
26+
def scope(self) -> dict:
27+
"""Return the scope."""
28+
return self._scope
29+
30+
@property
31+
def operation_context(self) -> dict:
32+
"""Return the per-operation context."""
33+
return self._operation_context

channels_graphql_ws/scope_as_context.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
class ScopeAsContext:
2626
"""Wrapper to make Channels `scope` appear as an `info.context`."""
2727

28-
def __init__(self, scope):
28+
def __init__(self, scope: dict):
2929
"""Remember given `scope`."""
3030
self._scope = scope
3131

0 commit comments

Comments
 (0)