Completed
Branch master (b389e4)
by Fox
01:43 queued 30s
created

publishing()   C

Complexity

Conditions 7

Size

Total Lines 49

Duplication

Lines 0
Ratio 0 %

Importance

Changes 7
Bugs 1 Features 0
Metric Value
cc 7
c 7
b 1
f 0
dl 0
loc 49
rs 5.5
1
# coding: utf-8
2
from __future__ import unicode_literals
3
from __future__ import absolute_import
4
5
import arrow
6
7
# django
8
from django.conf import settings
9
from django.utils.log import getLogger
10
11
# trigger happy
12
from django_th.services import default_provider
13
from django_th.models import TriggerService, update_result
14
15
16
logger = getLogger('django_th.trigger_happy')
17
18
default_provider.load_services()
19
20
21
def update_trigger(service):
22
    """
23
        update the date when occurs the trigger
24
        :param service: service object to update
25
    """
26
    now = arrow.utcnow().to(settings.TIME_ZONE).format(
27
        'YYYY-MM-DD HH:mm:ssZZ')
28
    TriggerService.objects.filter(id=service.id).update(date_triggered=now)
29
30
31
def log_update(service, to_update, status, count):
32
    """
33
        lets log everything at the end
34
        :param service: service object
35
        :param to_update: boolean to check if we have to update
36
        :param status: is everything worked fine ?
37
        :param count: number of data to update
38
        :type service: service object
39
        :type to_update: boolean
40
        :type status: boolean
41
        :type count: interger
42
    """
43
    if to_update:
44
        if status:
45
            msg = "{} - {} new data".format(service, count)
46
            update_result(service.id, msg="OK")
47
            logger.info(msg)
48
        else:
49
            msg = "{} AN ERROR OCCURS ".format(service)
50
            update_result(service.id, msg=msg)
51
            logger.warn(msg)
52
    else:
53
        logger.debug("{} nothing new ".format(service))
54
55
56
def publishing(service):
57
    """
58
        the purpose of this tasks is to get the data from the cache
59
        then publish them
60
        :param service: service object where we will publish
61
        :type service: object
62
    """
63
    # flag to know if we have to update
64
    to_update = False
65
    # flag to get the status of a service
66
    status = False
67
    # provider - the service that offer data
68
    # check if the service has already been triggered
69
    # if date_triggered is None, then it's the first run
70
    if service.date_triggered is None:
71
        logger.debug("first run {}".format(service))
72
        to_update = True
73
        status = True
74
    # run run run
75
    service_provider = default_provider.get_service(
76
        str(service.provider.name.name))
77
78
    # 1) get the data from the provider service
79
    module_name = 'th_' + \
80
                  service.provider.name.name.split('Service')[1].lower()
81
    kw = {'trigger_id': str(service.id), 'cache_stack': module_name}
82
    data = getattr(service_provider, 'process_data')(**kw)
83
    count_new_data = len(data) if data else 0
84
    if count_new_data > 0:
85
        # consumer - the service which uses the data
86
        service_consumer = default_provider.get_service(
87
                    str(service.consumer.name.name))
88
        kwargs = {'user': service.user}
89
        getattr(service_consumer, '__init__')(service.consumer.token,
90
                                              **kwargs)
91
        consumer = getattr(service_consumer, 'save_data')
92
93
        # 2) for each one
94
        for d in data:
95
            d['userservice_id'] = service.consumer.id
96
            # the consumer will save the data and return if success or not
97
            status = consumer(service.id, **d)
98
99
            to_update = True
100
        # let's log
101
    log_update(service, to_update, status, count_new_data)
102
    # let's update
103
    if to_update and status:
104
        update_trigger(service)
105