当前位置: 首页>>代码示例>>Python>>正文


Python client.Client类代码示例

本文整理汇总了Python中stravalib.client.Client的典型用法代码示例。如果您正苦于以下问题:Python Client类的具体用法?Python Client怎么用?Python Client使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Client类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: strava_upload

def strava_upload(tcxfiles, login=None):
    logging.basicConfig(level=logging.DEBUG)

    client = Client()

    creds = read_strava_auth_file()
    if login == None:
      if len(creds) > 0:
        print("found strava credentials for: " )
        n = 0
        for email in creds.keys():
          print(str(n) + " " + email)
          n += 1
   
        index_input = raw_input("enter the number corresponding to your email address.  Or just press enter to use your default browser to login\n")
        if re.match("\A\d+\Z", index_input):
          index = int(index_input)
          if index < len(creds):
            login = creds.keys()[index]
    
    if login and creds.has_key(login):
      client.access_token = creds[login]
    else:
      strava_authorize(client)

    for tcxfile in tcxfiles:
      r = post_file_to_strava(client, tcxfile)
      if(r.status_code == 401):
        print("invalid auth token, rerequesting authorization")
        strava_authorize(client)
        r = post_file_to_strava(client, tcxfile)

      if(r.status_code not in [200,201]):
        print("error uploading file.  HTTP response code: " + str(r.status_code))
        print(str(r.text))
开发者ID:kbb29,项目名称:schwinn810,代码行数:35,代码来源:tcx2strava.py

示例2: get_runs

def get_runs(request, n):
    """ Get most recent n runs associated with an account.
    """

    # Our admin object
    admin = _get_admin(request)

    # Be sure it exists
    if not admin.exists_document('strava_access_token'):
        request.response.status_int = 403
        return

    # Get the access token
    access_token = admin.get_document('strava_access_token')

    running_docs = {
        a:admin.get_document(a) for a in admin.list_documents() if a.startswith('run_')
    }

    strava_client = StravaClient(access_token=access_token['strava_access_token'])

    runs = []
    for a in strava_client.get_activities():
        if 'run_' + str(a.id) in running_docs:
            run = running_docs['run_' + str(a.id)]
        else:
            run = {
                'id': a.id,
                'timestamp': a.start_date_local.isoformat(),
                'duration': a.elapsed_time.total_seconds(),
                'distance': unithelper.miles(a.distance).num,
                'name': a.name,
                'description': a.description
            }
            if a.map.summary_polyline is not None:
                run['map_polyline'] = a.map.summary_polyline
            if a.start_latlng is not None and a.start_date is not None and 'darksky' in request.registry.settings['secrets']:
                fio = ForecastIO.ForecastIO(
                    request.registry.settings['secrets']['darksky']['darksky_secret'],
                    units=ForecastIO.ForecastIO.UNITS_US,
                    latitude=float(a.start_latlng[0]),
                    longitude=float(a.start_latlng[1]),
                    time=str(int(time.mktime(a.start_date.timetuple())))
                )
                if fio.has_currently():
                    currently = FIOCurrently.FIOCurrently(fio)
                    run['temperature'] = currently.temperature
                    run['weather_icon'] = currently.icon
            admin.create_document(run, doc_id='run_' + str(a.id))

        runs.append(run)
        if n is not None and len(runs) == n:
            break

    # Return appropriately
    request.response.status_int = 200
    return {
        'runs':
            runs
    }
开发者ID:jayfo,项目名称:tractdb-pyramid,代码行数:60,代码来源:storytelling_stravaview.py

示例3: get

    def get(request):
        """ Request -and store- a strava access token. """
        client = Client()

        # Extract the code from the response
        code = request.GET.get('code')
        access_token = client.exchange_code_for_token(
            client_id=settings.STRAVA_CLIENT_ID,
            client_secret=settings.STRAVA_CLIENT_SECRET,
            code=code
        )
        strava_athlete = client.get_athlete()

        try:
            athlete = Athlete.objects.get(strava_id=strava_athlete.id)
            athlete.strava_token = access_token
        except Athlete.DoesNotExist:
            athlete = Athlete(strava_id=strava_athlete.id, strava_token=access_token)
        athlete.save()

        cache_key = _get_cache_key(request)
        cache.delete(cache_key)
        redir_url = '{}?start_date={}&end_date={}'.format(
            reverse_lazy('strava-summary'),
            _get_start_date(request),
            _get_end_date(request)
        )
        return HttpResponseRedirect(redir_url)
开发者ID:Gidgidonihah,项目名称:strava-fitness-challenge-leaderboard,代码行数:28,代码来源:views.py

示例4: freshness

def freshness():
    c = Client(access_token=session['token'])
    try:
        limit = int(request.args.get("limit"))
    except (TypeError, ValueError):
        limit = None

    activities = list(c.get_activities(limit=limit))

    date = activities[-1].start_date.date()
    dates = []
    week_vals = []
    month_vals = []
    while date <= datetime.datetime.now().date():
        dates.append(datetime.datetime.combine(date, datetime.datetime.min.time()))
        min_week_date = date - datetime.timedelta(days=7)
        min_month_date = date - datetime.timedelta(days=30)
        M_PER_MILE = 1609
        week_vals.append(sum(float(a.distance) / M_PER_MILE for a in activities if a.start_date.date() <= date and a.start_date.date() > min_week_date))
        month_vals.append((7 / 30.0) * sum(float(a.distance) / M_PER_MILE for a in activities if a.start_date.date() <= date and a.start_date.date() > min_month_date))

        date += datetime.timedelta(days=1)

    data = [dates, week_vals, month_vals]
    return render_template('freshness.html', data=data)
开发者ID:matt-leach,项目名称:strava-reports,代码行数:25,代码来源:reports.py

示例5: send_run_to_strava

def send_run_to_strava():
    '''Ask whether to send a run to strava if it hasn't already.  Option to
    add a description.  Update on_strava field in database if successfully
    sent or prompted to do so if not sent.'''
    cfg.read(os.path.join(os.getenv('HOME'), '.config/strava.cfg'))
    access_token = cfg.get('Strava', 'access_token')
    client = Client()
    client.access_token = access_token
    runs = get_list_of_runs_not_on_strava()
    for run in runs:
        print run
        send = raw_input("Send this run to Strava? (Y|N): ")
        if (send[0] in ['Y', 'y']):
            start_time = raw_input(
                "What time did the activity start HH:MM:SS: ")
            date_of_activity = "%sT%sZ", (run.run_date, start_time)
            description = raw_input("Add an optional description: ")
            client.create_activity(run.name,
                                   ACTIVITY_TYPE,
                                   date_of_activity,
                                   run.time,
                                   description,
                                   unithelper.miles(run.distance))
            mark_run_as_on_strava(run.run_date, run.route_id, run.athlete_id)
            logging.info("Sent this activity to Strava: %s", run)
        else:
            update = raw_input("Update this run as on Strava (Y|N): ")
            if (update[0] in ['Y', 'y']):
                mark_run_as_on_strava(
                    run.run_date, run.route_id, run.athlete_id)
开发者ID:stvnwlsn,项目名称:runnin,代码行数:30,代码来源:runnin.py

示例6: login

def login():
    params = {
        'client_id': CLIENT_ID,
        'redirect_uri': HOSTNAME + '/oauth_authorized/'
    }
    client = Client()
    url = client.authorization_url(**params)
    return redirect(url)
开发者ID:kimeberz,项目名称:fitnezz,代码行数:8,代码来源:app.py

示例7: get

    def get(self):
        code = self.request.get('code')

        client = Client()
        access_token = client.exchange_code_for_token(client_id=conf.SV_CLIENT_ID, client_secret=conf.SV_CLIENT_SECRET, code=code)

        user_id = UserManager().AddUserToken(access_token)
        self.redirect('/user/{0}'.format(user_id))
开发者ID:pdiazv,项目名称:localgears,代码行数:8,代码来源:main.py

示例8: authorization

def authorization():
    code = request.args.get('code')
    client = Client()
    access_token = client.exchange_code_for_token(client_id=MY_STRAVA_CLIENT_ID,
                                                  client_secret=MY_STRAVA_CLIENT_SECRET,
                                                  code=code)
    response = redirect("/")
    response.set_cookie('access_token', access_token)
    return response
开发者ID:stuppie,项目名称:strava-pics,代码行数:9,代码来源:run.py

示例9: oauth_authorized

def oauth_authorized():
    client = Client()
    code = request.args.get('code')
    access_token = client.exchange_code_for_token(
        client_id=CLIENT_ID,
        client_secret=CLIENT_SECRET,
        code=code)
    session['access_token'] = access_token
    return redirect(url_for('index'))
开发者ID:kimeberz,项目名称:fitnezz,代码行数:9,代码来源:app.py

示例10: _get_club_members

    def _get_club_members():
        """ Get all athletes belonging to our club. """

        athlete = Athlete.objects.order_by('?').first()
        if not athlete:
            return []

        client = Client(access_token=athlete.strava_token)
        return client.get_club_members(settings.STRAVA_CHALLENGE_CLUB_ID)
开发者ID:Gidgidonihah,项目名称:strava-fitness-challenge-leaderboard,代码行数:9,代码来源:views.py

示例11: auth

def auth():
    access_token = request.cookies.get('access_token')
    if access_token:
        # Success!
        return show_images_demo()
    else:
        client = Client()
        url = client.authorization_url(client_id=MY_STRAVA_CLIENT_ID, redirect_uri=DOMAIN + '/authorization')
        print("DEBUG: auth url :" + url)
        return redirect(url, code=302)
开发者ID:stuppie,项目名称:strava-pics,代码行数:10,代码来源:run.py

示例12: get_images

def get_images(segment_id):
    access_token = request.cookies.get('access_token')
    if not access_token:
        return redirect("/")
    client = Client(rate_limiter=limiter.DefaultRateLimiter())
    client.access_token = access_token

    # look into this: https://github.com/saimn/sigal/
    images = get_images_from_segment(segment_id, client)
    return render_template('test.html', images=images)
开发者ID:stuppie,项目名称:strava-pics,代码行数:10,代码来源:run.py

示例13: check_oauth_token

 def check_oauth_token(cls, access_token):
     if not access_token:
         return False
     c = Client()
     c.access_token = access_token
     try:
         c.get_athlete()
     except HTTPError:
         return False
     else:
         return True
开发者ID:ZimmerHao,项目名称:arena,代码行数:11,代码来源:test_strava.py

示例14: auth

def auth():
    try:
        code = request.args["code"]
        c = Client()
        token = c.exchange_code_for_token(app.config['STRAVA_ID'], app.config['STRAVA_SECRET'], code)
    except (KeyError, requests.exceptions.HTTPError):
        return redirect("/")

    session["token"] = c.access_token = token
    a = c.get_athlete()  # Technically shouldn't be needed as the athlete details are returned in the oauth call
    session["athlete"] = {"firstname": a.firstname, "picture": a.profile_medium}
    return redirect("/")
开发者ID:matt-leach,项目名称:strava-reports,代码行数:12,代码来源:auth.py

示例15: get_user

    def get_user(self):
        client = Client()
        token = self.accessToken()

        if token is None:
            return None

        client.access_token = token
        athlete = client.get_athlete()
        return dict(first_name=athlete.firstname,
                    last_name=athlete.lastname,
                    email=athlete.email)
开发者ID:nkall,项目名称:SegTracker,代码行数:12,代码来源:auth.py


注:本文中的stravalib.client.Client类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。