コード例 #1
0
ファイル: application.py プロジェクト: 3thirty/strava_charts
def chart(type: str = 'average', metric: str = 'average_watts',
          period: str = 'week'):
    """
    Produce a page with a chart

    Accepted arguments:
        limit: Maximum number of activities to chart
        after: Only chart events with a start date after this (expected to be
               a date in format YYYY-mm-dd)
    """
    log = logging.getLogger('strava')

    if (request.query.force):
        force = True
    else:
        force = False

    token_store = CookieTokenStorage(request, response)

    try:
        strava = Strava(
            token_storage=token_store,
            debug=True,
            force=force
        )
    except AuthenticationException:
        session = bottle.request.environ.get('beaker.session')

        url = Authentication.start(
            session=session
        )

        redirect(url)

    chart = Chart()

    chart_title = "%s by %s" % (metric, period)
    chart.options.title.text = chart_title

    chart.labels.labels = []
    chart.data.Metric.data = []

    if (request.query.limit):
        activities = strava.getActivities(int(request.query.limit))
    else:
        activities = strava.getAllActivities()

    if (request.query.after):
        try:
            after_date = datetime.fromisoformat(request.query.after)
            activities = ActivityList.trimBeforeDate(activities, after_date)
        except ValueError:
            pass

    if (type == 'total'):
        data = activities.aggregateTotalMetricByPeriod(
                    metric=metric,
                    period=AggregationPeriod.strToEnum(period))
    else:
        data = activities.aggregateAverageMetricByPeriod(
                    metric=metric,
                    period=AggregationPeriod.strToEnum(period))

    log.debug("chart data: %s" % data)

    for label in data:
        chart.labels.labels.append(label)
        chart.data.Metric.data.append(data[label])

    chartJSON = chart.get()

    return template('chart', chartJSON=chartJSON)