-
-
Notifications
You must be signed in to change notification settings - Fork 84
/
generics.py
160 lines (130 loc) · 5.83 KB
/
generics.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
from copy import deepcopy
from django.db.models import Model
from functools import partial
from typing import Dict, Type, Optional, Set, List
from channels.db import database_sync_to_async
from rest_framework import status
from djangochannelsrestframework.consumers import APIConsumerMetaclass
from djangochannelsrestframework.decorators import action
from djangochannelsrestframework.generics import GenericAsyncAPIConsumer
from djangochannelsrestframework.mixins import RetrieveModelMixin
from djangochannelsrestframework.observer import ModelObserver
class _GenericModelObserver:
def __init__(self, func, **kwargs):
self.func = func
self._group_names = None
self._serializer = None
def bind_to_model(self, model_cls: Type[Model], name: str) -> ModelObserver:
observer = ModelObserver(func=self.func, model_cls=model_cls, partition=name)
observer.groups(self._group_names)
observer.serializer(self._serializer)
return observer
def groups(self, func):
self._group_names = func
return self
def serializer(self, func):
self._serializer = func
return self
class ObserverAPIConsumerMetaclass(APIConsumerMetaclass):
def __new__(mcs, name, bases, body) -> Type[GenericAsyncAPIConsumer]:
queryset = body.get("queryset", None)
if queryset is not None:
for attr_name, attr in body.items():
if isinstance(attr, _GenericModelObserver):
body[attr_name] = attr.bind_to_model(
model_cls=queryset.model,
name=f"{body['__module__']}.{name}.{attr_name}",
)
for base in bases:
for attr_name in dir(base):
attr = getattr(base, attr_name)
if isinstance(attr, _GenericModelObserver):
body[attr_name] = attr.bind_to_model(
model_cls=queryset.model,
name=f"{body['__module__']}.{name}.{attr_name}",
)
return super().__new__(mcs, name, bases, body)
class ObserverConsumerMixin(metaclass=ObserverAPIConsumerMetaclass):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.subscribed_requests = {} # type: Dict[str, Set[str]]
def _subscribe(self, request_id: str, groups: Set[str]):
for group in groups:
request_ids = self.subscribed_requests.get(group, set())
request_ids.add(request_id)
self.subscribed_requests[group] = request_ids
def _unsubscribe(self, request_id: str):
to_remove = []
for group, request_ids in self.subscribed_requests.items():
request_ids.remove(request_id)
if not request_ids:
to_remove.append(group)
for group in to_remove:
self.subscribed_requests.pop(group)
def _requests_for(self, group: Optional[str]):
all_request_ids = set()
if not group:
for request_ids in self.subscribed_requests.values():
all_request_ids = all_request_ids.union(request_ids)
return all_request_ids
return self.subscribed_requests.get(group, set())
class ObserverModelInstanceMixin(ObserverConsumerMixin, RetrieveModelMixin):
@action()
async def subscribe_instance(self, request_id=None, **kwargs):
if request_id is None:
raise ValueError("request_id must have a value set")
# subscribe!
instance = await database_sync_to_async(self.get_object)(**kwargs)
groups = set(await self.handle_instance_change.subscribe(instance=instance))
self._subscribe(request_id, groups)
return None, status.HTTP_201_CREATED
@action()
async def unsubscribe_instance(self, request_id=None, **kwargs):
if request_id is None:
raise ValueError("request_id must have a value set")
# subscribe!
instance = await database_sync_to_async(self.get_object)(**kwargs)
await self.handle_instance_change.unsubscribe(instance=instance)
self._unsubscribe(request_id)
return None, status.HTTP_204_NO_CONTENT
@_GenericModelObserver
async def handle_instance_change(
self, message: Dict, group=None, action=None, **kwargs
):
await self.handle_observed_action(
action=action,
group=group,
**message,
)
@handle_instance_change.groups
def handle_instance_change(self: ModelObserver, instance, *args, **kwargs):
# one channel for all updates.
yield "{}-model-{}-pk-{}".format(
self.func.__name__.replace("_", "."), self.model_label, instance.pk
)
async def handle_observed_action(
self, action: str, group: Optional[str] = None, **kwargs
):
"""
run the action.
"""
try:
await self.check_permissions(action, **kwargs)
except Exception as exc:
await self.handle_exception(exc, action=action, request_id=None)
for request_id in self._requests_for(group):
try:
reply = partial(self.reply, action=action, request_id=request_id)
if action == "delete":
await reply(data=kwargs, status=204)
# send the delete
continue
# the @action decorator will wrap non-async action into async ones.
response = await self.retrieve(
request_id=request_id, action=action, **kwargs
)
if isinstance(response, tuple):
data, status = response
await reply(data=data, status=status)
except Exception as exc:
await self.handle_exception(exc, action=action, request_id=request_id)