Completed
Push — master ( 9ed73f...7648fa )
by
unknown
01:21
created

get_month_range_from_dict()   A

Complexity

Conditions 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 12
rs 9.4285
cc 3
1
# coding: utf8
2
3
"""
4
This software is licensed under the Apache 2 license, quoted below.
5
6
Copyright 2014 Crystalnix Limited
7
8
Licensed under the Apache License, Version 2.0 (the "License"); you may not
9
use this file except in compliance with the License. You may obtain a copy of
10
the License at
11
12
    http://www.apache.org/licenses/LICENSE-2.0
13
14
Unless required by applicable law or agreed to in writing, software
15
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17
License for the specific language governing permissions and limitations under
18
the License.
19
"""
20
21
from functools import wraps
22
import datetime
23
import calendar
24
25
from singledispatch import singledispatch
26
from django_redis import get_redis_connection
27
from redis.exceptions import WatchError
28
from django.utils import timezone
29
30
from omaha.settings import KEY_PREFIX, KEY_LAST_ID
31
32
__all__ = ['get_sec_since_midnight', 'get_id']
33
34
redis = get_redis_connection('statistics')
35
36
37
def get_sec_since_midnight(date):
38
    """
39
    Return seconds since midnight
40
41
    >>> from datetime import datetime
42
    >>> get_sec_since_midnight(datetime(year=2014, month=1, day=1, second=42))
43
    42
44
    """
45
    midnight = date.replace(hour=0, minute=0, second=0, microsecond=0)
46
    delta = date - midnight
47
    return delta.seconds
48
49
50
def get_id(uuid):
51
    """
52
    >>> get_id('{8C65E04C-0383-4AE2-893F-4EC7C58F70DC}')
53
    1
54
    >>> get_id('{8C65E04C-0383-4AE2-893F-4EC7C58F70DC}')
55
    1
56
    """
57
    id = redis.get('{}:{}'.format(KEY_PREFIX, uuid))
58
    if id is None:
59
        id = create_id(uuid)
60
    return int(id)
61
62
63
def create_id(uuid):
64
    """
65
    >>> create_id('{8C65E04C-0383-4AE2-893F-4EC7C58F70DC}')
66
    1
67
    """
68
    with redis.pipeline() as pipe:
69
        while True:
70
            try:
71
                pipe.watch(KEY_LAST_ID)
72
                current_id = pipe.get(KEY_LAST_ID) or 0
73
                next_id = int(current_id) + 1
74
                pipe.multi()
75
                pipe.set(KEY_LAST_ID, next_id)
76
                pipe.execute()
77
78
                redis.set('{}:{}'.format(KEY_PREFIX, uuid), next_id)
79
                return next_id
80
            except WatchError:
81
                continue
82
            except:
83
                raise
84
85
86
def valuedispatch(func):
87
    _func = singledispatch(func)
88
89
    @wraps(func)
90
    def wrapper(*args, **kwargs):
91
        return _func.registry.get(args[0], _func)(*args, **kwargs)
92
93
    wrapper.register = _func.register
94
    wrapper.dispatch = _func.dispatch
95
    wrapper.registry = _func.registry
96
    return wrapper
97
98
99
def make_piechart(id, data, unit='users'):
100
    xdata = [i[0] for i in data]
101
    ydata = [i[1] for i in data]
102
103
    extra_serie = {
104
        "tooltip": {"y_start": "", "y_end": " " + unit},
105
    }
106
    chartdata = {'x': xdata, 'y1': ydata, 'extra1': extra_serie}
107
    charttype = "pieChart"
108
    chartcontainer = 'chart_container_%s' % id  # container name
109
110
    data = {
111
        'charttype': charttype,
112
        'chartdata': chartdata,
113
        'chartcontainer': chartcontainer,
114
        'extra': {
115
            'x_is_date': False,
116
            'x_axis_format': '',
117
            'tag_script_js': True,
118
            'jquery_on_ready': False,
119
        }
120
    }
121
    return data
122
123
124
def make_discrete_bar_chart(id, data):
125
    xdata = [i[0] for i in data]
126
    ydata = [i[1] for i in data]
127
128
    extra_serie1 = {"tooltip": {"y_start": "", "y_end": " cal"}}
129
    chartdata = {
130
        'x': xdata, 'name1': '', 'y1': ydata, 'extra1': extra_serie1,
131
    }
132
    charttype = "discreteBarChart"
133
    chartcontainer = 'chart_container_%s' % id  # container name
134
    data = {
135
        'charttype': charttype,
136
        'chartdata': chartdata,
137
        'chartcontainer': chartcontainer,
138
        'extra': {
139
            'x_is_date': False,
140
            'x_axis_format': '',
141
            'tag_script_js': True,
142
            'jquery_on_ready': True,
143
        },
144
    }
145
    return data
146
147
148
def get_month_range_from_dict(source):
149
    """
150
    :param request: dictionary with keys 'start' and 'end
151
    :return: a tuple of datatime objects in the form (start, end)
152
    """
153
    now = timezone.now()
154
    start = source.get('start')
155
    if not start:
156
        start = datetime.datetime(now.year-1, now.month+1, 1) if now.month != 12 else datetime.datetime(now.year, now.month, 1)
157
158
    end = source.get('end', datetime.datetime(now.year, now.month, calendar.monthrange(now.year, now.month)[1]))
159
    return start, end
160