def api_calls_monthly(request): ignore_internal_keys = parse_bool_param(request, "ignore_internal_keys", True) keys_issued_period = _keys_issued_date_range() earliest_month = (keys_issued_period["earliest"].year, keys_issued_period["earliest"].month) latest_month = (keys_issued_period["latest"].year, keys_issued_period["latest"].month) monthly = {} for (year, month) in cycle_generator(cycle=(1, 12), begin=earliest_month, end=latest_month): monthly[(year, month)] = {"year": year, "month": month, "calls": 0} qry = Report.objects if ignore_internal_keys: qry = exclude_internal_key_reports(qry) daily_aggs = qry.values("date").annotate(calls=Sum("calls")) for daily in daily_aggs: dt = daily["date"] month = (dt.year, dt.month) monthly[month]["calls"] += daily["calls"] result = {"monthly": monthly.values()} return HttpResponse(content=json.dumps(result), status=200, content_type="application/json")
def _cumulative_by_date(model, datefield): ''' Given a model and date field, generate monthly cumulative totals. ''' monthly_counts = defaultdict(int) for obj in model.objects.all().order_by(datefield): datevalue = getattr(obj, datefield) monthkey = (datevalue.year, datevalue.month) monthly_counts[monthkey] += 1 if len(monthly_counts) == 0: return [] earliest_month = min(monthly_counts.iterkeys()) latest_month = max(monthly_counts.iterkeys()) accumulator = 0 cumulative_counts = [] for (year, month) in cycle_generator(cycle=(1, 12), begin=earliest_month, end=latest_month): mcount = monthly_counts.get((year, month), 0) accumulator += mcount cumulative_counts.append([datetime.date(year, month, 1), accumulator]) return cumulative_counts