record.py 1007 Bytes
Newer Older
1 2 3 4
import persisting_theory


class ActivityRegistry(persisting_theory.Registry):
Agate's avatar
Agate committed
5
    look_into = "activities"
6 7 8

    def _register_for_model(self, model, attr, value):
        key = model._meta.label
Agate's avatar
Agate committed
9
        d = self.setdefault(key, {"consumers": []})
10 11 12 13
        d[attr] = value

    def register_serializer(self, serializer_class):
        model = serializer_class.Meta.model
Agate's avatar
Agate committed
14
        self._register_for_model(model, "serializer", serializer_class)
15 16 17 18
        return serializer_class

    def register_consumer(self, label):
        def decorator(func):
Agate's avatar
Agate committed
19
            consumers = self[label]["consumers"]
20 21 22
            if func not in consumers:
                consumers.append(func)
            return func
Agate's avatar
Agate committed
23

24 25 26 27 28 29 30 31
        return decorator


registry = ActivityRegistry()


def send(obj):
    conf = registry[obj.__class__._meta.label]
Agate's avatar
Agate committed
32
    consumers = conf["consumers"]
33 34
    if not consumers:
        return
Agate's avatar
Agate committed
35
    serializer = conf["serializer"](obj)
36 37
    for consumer in consumers:
        consumer(data=serializer.data, obj=obj)