<s> from __future__ import absolute_import <EOL> import datetime <EOL> import operator <EOL> from django import http <EOL> from django . conf import settings <EOL> from django . shortcuts import render <EOL> from django . utils import simplejson <EOL> from django . forms . models import model_to_dict <EOL> from django . views . decorators . cache import cache_page <EOL> from . models import Metric <EOL> TEN_MINUTES = <NUM_LIT> * <NUM_LIT:10> <EOL> @ cache_page ( TEN_MINUTES ) <EOL> def index ( request ) : <EOL> metrics = [ ] <EOL> for MC in Metric . __subclasses__ ( ) : <EOL> metrics . extend ( MC . objects . filter ( show_on_dashboard = True ) ) <EOL> metrics = sorted ( metrics , key = operator . attrgetter ( '<STR_LIT>' ) ) <EOL> data = [ ] <EOL> for metric in metrics : <EOL> latest = metric . data . latest ( ) <EOL> data . append ( { '<STR_LIT>' : metric , '<STR_LIT>' : latest } ) <EOL> return render ( request , '<STR_LIT>' , { '<STR_LIT:data>' : data } ) <EOL> @ cache_page ( TEN_MINUTES ) <EOL> def metric_detail ( request , metric_slug ) : <EOL> metric = _find_metric ( metric_slug ) <EOL> return render ( request , '<STR_LIT>' , { <EOL> '<STR_LIT>' : metric , <EOL> '<STR_LIT>' : metric . data . latest ( ) , <EOL> } ) <EOL> @ cache_page ( TEN_MINUTES ) <EOL> def metric_json ( request , metric_slug ) : <EOL> metric = _find_metric ( metric_slug ) <EOL> try : <EOL> daysback = int ( request . GET [ '<STR_LIT>' ] ) <EOL> except ( TypeError , KeyError , ValueError ) : <EOL> daysback = <NUM_LIT:30> <EOL> d = datetime . datetime . now ( ) - datetime . timedelta ( days = daysback ) <EOL> doc = model_to_dict ( metric ) <EOL> doc [ '<STR_LIT:data>' ] = metric . gather_data ( since = d ) <EOL> return http . HttpResponse ( <EOL> simplejson . dumps ( doc , indent = <NUM_LIT:2> if settings . DEBUG else None ) , <EOL> content_type = "<STR_LIT:application/json>" , <EOL> ) <EOL> def _find_metric ( slug ) : <EOL> for MC in Metric . __subclasses__ ( ) : <EOL> try : <EOL> return MC . objects . get ( slug = slug ) <EOL> except MC . DoesNotExist : <EOL> continue <EOL> raise http . Http404 ( ) </s>
