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


Python Client.access_token方法代码示例

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


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

示例1: send_run_to_strava

# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import access_token [as 别名]
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,代码行数:32,代码来源:runnin.py

示例2: strava_upload

# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import access_token [as 别名]
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,代码行数:37,代码来源:tcx2strava.py

示例3: get_images

# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import access_token [as 别名]
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,代码行数:12,代码来源:run.py

示例4: check_oauth_token

# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import access_token [as 别名]
 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,代码行数:13,代码来源:test_strava.py

示例5: get_user

# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import access_token [as 别名]
    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,代码行数:14,代码来源:auth.py

示例6: authorized

# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import access_token [as 别名]
def authorized():
	# get access token to make requests
	client = Client()
	code = request.args.get('code')
	client.access_token = client.exchange_code_for_token(client_id=creds.client_id, client_secret=creds.client_secret, code=code) # add id and secret

	# get data
	today = datetime.datetime.strptime(str(datetime.date.today()), "%Y-%m-%d")
	one_month_ago = today - dateutil.relativedelta.relativedelta(months=1)
	athlete = client.get_athlete()
	activities = client.get_activities(after=one_month_ago)
	rides = toolkit.get_activity_types(activities, 'ride')
	runs = toolkit.get_activity_types(activities, 'run')
	ride_set = ActivitySet("Rides", rides)
	run_set = ActivitySet("Runs", runs)
	return render_template('main.html', athlete=athlete, activity_sets=[ride_set, run_set])
开发者ID:chorn21,项目名称:strava-facts,代码行数:18,代码来源:start.py

示例7: handle

# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import access_token [as 别名]
	def handle(self, *args, **options):
		client = Client()
		client.access_token = '20bf9e2864c1411d17d9cab8c11aa8dbe626aedd'
		cityEntries = City.objects.all()
		resetPlaceChanges = False
		if not cityEntries:
			cityEntries = createDefaultCitySegments()
			resetPlaceChanges = True

		for city in cityEntries:
			updater = CityLeaderboardUpdater(city, client)
			updater.update()

		# Delete placement changes if data has just been reset
		if resetPlaceChanges:
			placementChanges = PlacementChange.objects.all()
			for pc in placementChanges.iterator():
				pc.delete()
		print("Updated at " + str(timezone.now()))
开发者ID:nkall,项目名称:ClimbersCrown,代码行数:21,代码来源:update.py

示例8: file

# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import access_token [as 别名]
from stravalib.client import Client
from stravalib.attributes import LatLon
import units

LOGIN = file("access_token").read().strip()
BIKES = {
	"Madone": "b1258359",
	"Secteur": "b1708741",
	"Random": "b1209450",
}
# Strava rounds to two decimals which isn't terribly precise but at least easy
# for comparisons.
WORK = LatLon(lat=51.49, lon=-0.15)

client = Client()
client.access_token = LOGIN

def build_updates(act):
	ret = {}

	if act.type != act.RIDE:
		if (act.start_latlng == WORK and
		    act.start_date_local.weekday() <= 4):
			ret["name"] = "Walking commute"
			ret["commute"] = True
			ret["activity_type"] = act.WALK

		# I don't record walks that often anyway.
		return
	
	segments = [se.segment.id for se in act.segment_efforts]
开发者ID:Wilm0r,项目名称:strava-mv,代码行数:33,代码来源:strava-mv.py

示例9: int

# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import access_token [as 别名]
        client_id = cfg.get("StravaClient", "ClientId")
        client_secret = cfg.get("StravaClient", "ClientSecret")
        port = int(cfg.get("Application", "Port"))
        
        # setup webserver for authentication redirect
        httpd = http.server.HTTPServer(('127.0.0.1', port), AuthHandler)

        # The url to authorize from
        authorize_url = client.authorization_url(client_id=client_id, redirect_uri='http://localhost:{port}/authorized'.format(port=port), scope='view_private,write')
        # Open the url in your browser
        webbrowser.open(authorize_url, new=0, autoraise=True)

        # wait until you click the authorize link in the browser
        httpd.handle_request()
        code = httpd.code

        # Get the token
        token = client.exchange_code_for_token(client_id=client_id, client_secret=client_secret, code=code)

        # Now store that access token in the config
        cfg.set("UserAcct", "Token", token)
        with open("stravamng.cfg", "w") as cfg_file:
            cfg.write(cfg_file)

    client.access_token = token

    # do stuff
    athlete = client.get_athlete()
    print("For {id}, I now have an access token {token}".format(id=athlete.id, token=token))

开发者ID:odontomachus,项目名称:stravalib_demo,代码行数:31,代码来源:stravamng.py

示例10: Client

# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import access_token [as 别名]
## import libraries
from stravalib.client import Client
from cartodb import CartoDBAPIKey, CartoDBException
import numpy as np
import datetime
import time
from polyline.codec import PolylineCodec
from geojson import Feature, LineString

## Strava connection
client = Client()
client.access_token = 'd47099a29b2f3539e1c21af6d820e33a109a079e'

## CartoDB connection
API_KEY ='cad54ea0c580a0c554b9e9562157e7c9bd9f37b0'
cartodb_domain = 'geodarcy'
cl = CartoDBAPIKey(API_KEY, cartodb_domain)

## remove duplicate rows
cl.sql('DELETE FROM wbstrava WHERE cartodb_id IN (SELECT cartodb_id FROM (SELECT cartodb_id, ROW_NUMBER() OVER (partition BY segment_id ORDER BY cartodb_id) AS rnum FROM wbstrava) t WHERE t.rnum > 1);')

## find segments with no geometry
queryResult = cl.sql('select segment_id from wbstrava where the_geom is null')
currentSegments = [x['segment_id'] for x in queryResult['rows']]
for id in currentSegments:
  try:
    segmentGeojson = PolylineCodec().decode(client.get_segment(id).map.polyline)
    flippedGeojson = [[x[1], x[0]] for x in segmentGeojson]
    inputGeojson = '{"coordinates": ' + str(flippedGeojson) + ', "type": "LineString", "crs":{"type":"name","properties":{"name":"EPSG:4326"}}}'
    cl.sql('UPDATE wbstrava SET the_geom = ST_GeomFromGeoJSON(\'' + inputGeojson + '\') WHERE segment_id=' + str(id))
  except Exception as e:
开发者ID:geodarcy,项目名称:winterbiking,代码行数:33,代码来源:updateRatios.py

示例11: scrape_strava

# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import access_token [as 别名]

#.........这里部分代码省略.........
    # Strava auth callbacks will hit this host and port. Change the port if you
    # need to avoid port conflicts with other servers.
    CALLBACK_PORT = 36724
    # Where to store your Strava activity info and the Strava auth token.
    ACTIVITIES_TABLE = 'strava_activities'
    TOKEN_TABLE = 'strava_token'

    # Scraper body begins here.

    import config

    import webbrowser
    import logging
    from cgi import parse_qs
    from wsgiref.simple_server import make_server

    import dataset
    from stravalib.client import Client
    from stravalib import unithelper
    from units import unit

    # And here's the rest of the scraper.

    def get_new_token():
        authorize_url = client.authorization_url(
            client_id=CLIENT_ID,
            redirect_uri=('%s:%s' % (config.SERVER_HOST, CALLBACK_PORT))
        )
        webbrowser.open(authorize_url)
        print('Click here to authorize me to access your Strava activities: %s'
              % authorize_url)
        make_server('localhost', CALLBACK_PORT, auth_listener).handle_request()

    def auth_listener(environ, start_response):
        start_response("200 OK", [('Content-Type', 'text/plain')])
        parameters = parse_qs(environ.get('QUERY_STRING', ''))
        code_received(parameters['code'][0])
        return ['Got your authorization from Strava! '
                'You can close this window now.'
                .encode('utf-8')]

    def code_received(code):
        token = client.exchange_code_for_token(client_id=CLIENT_ID,
                                               client_secret=CLIENT_SECRET,
                                               code=code)
        tokens.insert({'token': token})
        print('Got your authorization from Strava. Thanks!')
        query_strava()

    def avg_speed_to_mins(avg_speed):
        sec_per_meter = unit('s') / unit('m')
        min_per_mile = unit('min') / unit('mi')
        pace = min_per_mile(sec_per_meter(avg_speed.get_num() ** -1))
        return pace.get_num()

    def query_strava():
        print('Querying Strava...')

        table = db[ACTIVITIES_TABLE]
        activity_summaries = [a for a in client.get_activities()]
        num_added = 0

        for a_summary in activity_summaries:
            if table.find_one(strava_id=a_summary.id):
                break
            a = client.get_activity(a_summary.id)
            activity_data = {
                'strava_id': a.id,
                'name': a.name,
                'type': a.type,
                'start_date': a.start_date.isoformat(),
                'distance_mi': float(unithelper.miles(a.distance)),
                'elapsed_sec': a.elapsed_time.total_seconds(),
                'pace_mins_per_mi': avg_speed_to_mins(a.average_speed),
                'polyline': a.map.summary_polyline
            }
            print('Added %s: %s' % (a.type, a.name))
            num_added += 1
            table.insert(activity_data)

        print('Done! %s activities added.' % num_added)

    # Stravalib throws lots of warnings for schema issues on Strava's end.
    # These warnings don't impact us so let's ignore them.
    logger_names = [k for k in logging.Logger.manager.loggerDict.keys() if
                    k.startswith('stravalib')]
    for logger_name in logger_names:
        logging.getLogger(logger_name).setLevel(logging.ERROR)

    client = Client()

    db = dataset.connect(config.DB_URI)
    tokens = db[TOKEN_TABLE]
    token_obj = tokens.find_one()

    if token_obj:
        client.access_token = token_obj['token']
        query_strava()
    else:
        get_new_token()
开发者ID:mplewis,项目名称:narcissa,代码行数:104,代码来源:strava.py

示例12: Client

# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import access_token [as 别名]
#!/bin/python
import ConfigParser
import json
import io
from stravalib.client import Client

config = ConfigParser.ConfigParser()
client = Client()

config.read('config.ini')
client.access_token = config.get("access","access_token")
app_friends = config.get("app","friends")
redis_host = config.get("access", "redis_host")

# get my profile
#curr_athlete = client.get_athlete()
# inspect the athlete object
#print(type(curr_athlete))
#print(dir(curr_athlete))

# get another athlete profile
#curr_athlete = client.get_athlete(4658463)
#print(curr_athlete)

# get a segment
#curr_segment = client.get_segment(11493495)
#print(type(curr_segment))
#print(dir(curr_segment))
#print(curr_segment)
# get a segment leaderboard
#curr_segmentldr = client.get_segment_leaderboard(11493495)
开发者ID:sirmdub,项目名称:stravaNotifier,代码行数:33,代码来源:samples.py

示例13: Client

# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import access_token [as 别名]
from stravalib.client import Client
from stravalib import unithelper
import pandas as pd
import cPickle as pickle
from os.path import join, exists
from os import makedirs, getcwd
from datetime import datetime

client = Client()
client.access_token = "8ad469fc76e136a0d5a40f0ad10ea0e8282ef6e5"

me = client.get_athlete()

print me.email

def to_miles(dist):
    return float(unithelper.miles(dist))

def to_mph(mps):
    return float(unithelper.mph(act.average_speed))

def echo(v):
    return v

#TODO Convert moving time properly, want in a timedelta really

#TODO To do proper clustering, need columns as lat then long, and rows as runs
# but how to deal with runs of different lengths?
# I think all streams have the same number of points?  
# Which isn't going to be great, but givem that different routes, even if stretched out/shrunk, have different shapes
# then distinct ones should stay that way, so might be ok
开发者ID:jurasource,项目名称:strava-analysis,代码行数:33,代码来源:main.py

示例14: Client

# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import access_token [as 别名]
"""
Created on Sat Aug  1 11:08:17 2015

@author: fraidylevilev
"""

# My access token: c2f218e5c3a9af9a3e0389d3e539e197f19f650e
# My athlete id: 9753705

from stravalib.client import Client
# import the strava library

client = Client()

# Input your access token below!
client.access_token = 'c2f218e5c3a9af9a3e0389d3e539e197f19f650e'
#this is me
athlete = client.get_athlete(9753705)
print("For {id}, I now have an access token {token}".format(id = athlete, token = client.access_token))

import requests
import pandas as pd
import numpy as np
import time
import sys

#calling strava api
base_url = 'https://www.strava.com/api'
#using api to get efforts on a segment
segment_url = base_url + '/v3/segments/{0}/all_efforts'
extra_headers = {'Authorization' : 'Bearer {0}'.format(access_token)}
开发者ID:fraidaL,项目名称:SF_DAT_15_WORK,代码行数:33,代码来源:untitled0.py


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