def aggregate(self): conf = self.config.get(self.group) format = conf.get('format') # Current datetime formatting function freq = conf.get('freq') # Current frequency fbegin = conf.get('fbegin') # Converter to begin of period fend = conf.get('fend') # Converter to end of period # Align entered datetimes by current group dtbegin = fbegin(self.fm) dtend = fend(self.to) # Generate some test random data #checkpoints = times.datetime_range(times.MINUTELY, dtstart=dtbegin, until=dtend) #clicks = [random.choice(checkpoints) for _x in range(10)] #shows = [random.choice(checkpoints) for _x in range(10000)] # But this is real data from backend acts = actions.get_actions_range(dtbegin, dtend, **self.kwargs) shws = shows.get_shows_range(dtbegin, dtend, **self.kwargs) # List of all times in interval with period depending on group keys = times.datetime_range(freq, dtstart=dtbegin, until=dtend) # Fill result dict with test data result = dict([(key, [0, 0]) for key in keys]) for act in acts: result[fbegin(act.creation_time)][0] += 1 for shw in shws: result[fbegin(shw.show_time)][1] += 1 # This magic expression transforms dict to list of dicts sorted by datetime return [dict(time=format(key), clicks=value[0], shows=value[1]) \ for key, value in sorted(result.items(), key=lambda item: item[0])]
def json_get_ctr(**kwargs): try: fm = convert.to_datetime(request.args.get('from') + ':00') to = convert.to_datetime(request.args.get('to') + ':00') if fm > to: raise ValueError except: return u'Неверно указан интервал', 400 try: group = request.args.get('group') if group not in ('hour', 'day', 'month', 'year'): raise ValueError except: return u'Неверно указана группировка', 400 if group == 'hour': replacer = times.begin_of_hour formatter = lambda d: d.strftime('%d.%m.%y') if d.hour == 0 else d.strftime('%H:00') freq = times.HOURLY elif group == 'day': replacer = times.begin_of_day formatter = lambda d: d.strftime('%d.%m.%y') freq = times.DAILY elif group == 'month': replacer = times.begin_of_month formatter = lambda d: d.strftime('%m.%Y') freq = times.MONTHLY elif group == 'year': replacer = times.begin_of_year formatter = lambda d: d.strftime('%Y') freq = times.YEARLY #fm = replacer(fm) #to = replacer(to) stats = actions.stats.get_stats_ctr(fm, to, group, **kwargs) keys = times.datetime_range(freq, dtstart=replacer(fm), until=replacer(to)) values = dict([(key, (0, 0, 0.0)) for key in keys]) # if len(stats) != len (keys) else dict() for stat in stats: values[replacer(stat.time)] = (stat.shows, stat.actions, round(stat.ctr, 4)) result = [dict(time=formatter(key), shows=value[0], clicks=value[1], ctr=value[2]) \ for key, value in sorted(values.items(), key=lambda item: item[0])] return jsonify(values=result)