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


Python Client.access_token方法代码示例

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


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

示例1: main

# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import access_token [as 别名]
def main():
    assert len(args.athlete_ids) == len(args.access_tokens)

    logger.info("app id: %i, fetching friends for ids %s" % \
                (args.id_strava_app, str(args.athlete_ids)))
    
    for i in range( len(args.access_tokens) ):
        client              = Client()
        client.access_token = args.access_tokens[i]
        athlete_id          = args.athlete_ids[i]


        time.sleep(TIME_PAUSE)
        friends   = [ friend.id for friend in client.get_athlete_friends() ]
        time.sleep(TIME_PAUSE)
        followers = [ follower.id for follower in client.get_athlete_followers() ]

        add_friends_to_db(conn, athlete_id, friends,   type="friend")
        add_friends_to_db(conn, athlete_id, followers, type="follower")
        
    logger.info("Done.") 
开发者ID:williaster,项目名称:strava_buddies,代码行数:23,代码来源:strava_friends_populator.py

示例2: main

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

	# Creating a log file and a logging function
	log = open("log.txt","a+")
	now = str(datetime.now())
	def logger (message):
		log.write(now + " | " + message + "\n")
		print message

	# Opening the connection to Strava
	logger("Connecting to Strava")
	client = Client()

	# You need to run the strava_local_client.py script - with your application's ID and secret - to generate the access token.
	access_token = "your_token" # replace this with your token
	client.access_token = access_token
	athlete = client.get_athlete()
	logger("Now authenticated for " + athlete.firstname + " " + athlete.lastname)

	# Creating an archive folder to put uploaded .gpx files
	archive = "../archive"

	# Function to convert the HH:MM:SS in the Runkeeper CSV to seconds
	def duration_calc(duration):
		# Splits the duration on the :, so we wind up with a 3-part array
		split_duration = str(duration).split(":")
		# If the array only has 2 elements, we know the activity was less than an hour
		if len(split_duration) == 2:
			hours = 0
			minutes = int(split_duration[0])
			seconds = int(split_duration[1])
		else:
			hours = int(split_duration[0])
			minutes = int(split_duration[1])
			seconds = int(split_duration[2])
		
		total_seconds = seconds + (minutes*60) + (hours*60*60)
		return total_seconds

	# Translate RunKeeper's activity codes to Strava's, could probably be cleverer
	def activity_translator(rk_type):
		if rk_type == "Running":
			return "Run"
		elif rk_type == "Cycling":
			return "Ride"
		elif rk_type == "Hiking":
			return "Hike"
		elif rk_type == "Walking":
			return "Walk"
		elif rk_type == "Swimming":
			return "Swim"
		elif rk_type == "Elliptical":
			return "Elliptical"
		else:
			return "None"
		# feel free to extend if you have other activities in your repertoire; Strava activity codes can be found in their API docs 


	# We open the cardioactivities CSV file and start reading through it
	with open('cardioActivities.csv', 'rb') as csvfile:
		activities = csv.reader(csvfile)
		activity_counter = 0
		for row in activities:
			if activity_counter >= 599:
				logger("Upload count at 599 - pausing uploads for 15 minutes to avoid rate-limit")
				time.sleep(900)
				activity_counter = 0
			else:
				pass
			if row[0] == "Date":
				pass
			else:
				# if there is a gpx file listed, find it and upload it
				if ".gpx" in row[11]:
					gpxfile = row[11]
					strava_activity_type = activity_translator(str(row[1]))
					if gpxfile in os.listdir('.'):
						logger("Uploading " + gpxfile)
						try:
							upload = client.upload_activity(
								activity_file = open(gpxfile,'r'),
								data_type = 'gpx',
								private = False,
								description = row[10],
								activity_type = strava_activity_type
								)
						except exc.ActivityUploadFailed as err:
							logger("Uploading problem raised: {}".format(err))
							errStr = str(err)
							# deal with duplicate type of error, if duplicate then continue with next file, else stop
							if errStr.find('duplicate of activity'):
								logger("Moving dulicate activity file {}".format(gpxfile))
								shutil.move(gpxfile,archive)
								isDuplicate = True
								logger("Duplicate File " + gpxfile)
							else:
								exit(1)

						except ConnectionError as err:
							logger("No Internet connection: {}".format(err))
#.........这里部分代码省略.........
开发者ID:mehagel,项目名称:strava-uploader,代码行数:103,代码来源:uploader.py

示例3: print

# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import access_token [as 别名]
import os
import fnmatch
import shutil
from requests.exceptions import ConnectionError, HTTPError
from datetime import datetime,  timedelta

# First, load settings from file
print("Loading settings...")
with open("settings.json", "r") as f:
    settings = json.load(f)

# Then, connect to user Strava account.
try:
   print("Connecting to Strava...")
   StravaClient = Client()
   StravaClient.access_token = settings.get('strava_token')

   # You're logged in !
   StravaAthlete = StravaClient.get_athlete()
   print("Hello, {} {}.\nYou are now connected to Strava.".format(StravaAthlete.firstname,  StravaAthlete.lastname))
except HTTPError as err:
   print("Connecting problem: {}".format(err))
   exit(1)

# Now we'll try to find activity(ies) to upload.
tcxStorageDir = settings.get('archives_dir') # Where TCX files are stored
Debug = False # If we need to have some more informations...
#Debug = True
Year = datetime.now().strftime("%Y") # This exists because TCX files are like : 2015-06-06T15-23-01.000Z_Walking.tcx
Exclude = ('UploadedToStrava', 'Endomondo', 'runtastic2strava') # List directories we don't want do search into
开发者ID:nah-ko,项目名称:myStravaTCXPush,代码行数:32,代码来源:pushStrava.py

示例4: main

# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import access_token [as 别名]
def main():
    assert len(args.athlete_ids) == len(args.access_tokens)

    logger.info("app id: %i, fetching activities for ids %s" % \
                (args.id_strava_app, str(args.athlete_ids)))
    
    for i in range( len(args.access_tokens) ): # for each athlete
        client              = Client()
        client.access_token = args.access_tokens[i]
        athlete_id          = args.athlete_ids[i]
        
        # get summary activities first (filterd before detailed activity call)
        time.sleep(TIME_PAUSE)
        activity_ids = get_user_activities(client) 

        # now fetch detailed versions, add to db
        detailed_activites = []
        activity_to_segments = {} # { act_id: 
                                  #    { seg_id : 
                                  #       { "distance" : x, "grade" : y }, }, }

        segment_ranks = {}        # { seg_id : { "auth_athlete_rank" : auth_rank,
                                  #              "other_athletes"    : { other_id : other_rank, } } }
        for act_id in activity_ids:
	    try:
                 activity_to_segments[act_id] = {}

                 time.sleep(TIME_PAUSE)
            
                 detailed_activity = client.get_activity( act_id )
                 detailed_activites.append( detailed_activity )
		 
                 for seg_effort in detailed_activity.segment_efforts:
                     segment   = seg_effort.segment
                     seg_id    = int(segment.id)
                     seg_dist  = float( unithelper.miles(segment.distance) )
                     seg_grade = segment.average_grade
                     seg_dct   = { "distance" : seg_dist, "grade" : seg_grade }

                     activity_to_segments[act_id][seg_id] = seg_dct

                     if segment_ranks.has_key(seg_id): # already have ranks
                         continue                      # might be overlap between activities
                     else:
                         try: # some = hazardous = error
                             time.sleep(TIME_PAUSE) # now get ranks for this segment
                             leaderboard_entries = \
                                 client.get_segment_leaderboard(seg_id, 
                                                                top_results_limit=1).entries
                             segment_ranks[seg_id] = { "auth_athlete_rank" : -1,
                                                       "other_athletes" : {} }

                             for entry in leaderboard_entries:
                                 if entry.athlete_id == athlete_id: 
                                     segment_ranks[seg_id]["auth_athlete_rank"] = entry.rank
                                     continue
                            
                                 other_id   = entry.athlete_id
                                 other_rank = entry.rank
                                 segment_ranks[seg_id]["other_athletes"][other_id] = other_rank

                         except Exception, e:
                             logger.warning("Error with segment_id %i, removing from activity,"\
                                            " trace:\n %s" % (seg_id, traceback.print_exc()))
                             activity_to_segments[act_id].pop(seg_id)
                             continue
		 if len(activity_to_segments[act_id]) > 0:
                     add_activity(conn, athlete_id, detailed_activity) # if made it here, okay
		 else:
		     logger.info("No segments for activity %i, skipping" % act_id)

	    except Exception, e: # occurs with wrong privaleges, eg private activity
	        logger.warning("Error with activity %i for athlete %i, popping. tracebac:\n%s" % \
				(act_id, athlete_id, traceback.print_exc()))
		activity_to_segments.pop(act_id)
开发者ID:williaster,项目名称:strava_buddies,代码行数:77,代码来源:strava_activity_populator.py

示例5: open

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

# Creating a log file and a logging function
log = open("log.txt","a+")
now = str(datetime.now())
def logger (message):
	log.write(now + " | " + message + "\n")
	print message

# Opening the connection to Strava
logger("Connecting to Strava")
client = Client()

# You need to run the strava_local_client.py script - with your application's ID and secret - to generate the access token.
access_token = "your_token" # replace this with your token
client.access_token = access_token
athlete = client.get_athlete()
logger("Now authenticated for " + athlete.firstname + " " + athlete.lastname)

# Creating an archive folder to put uploaded .gpx files
archive = "../archive"

# Function to convert the HH:MM:SS in the Runkeeper CSV to seconds
def duration_calc(duration):
	
	# Splits the duration on the :, so we wind up with a 3-part array
	split_duration = str(duration).split(":")

	# If the array only has 2 elements, we know the activity was less than an hour
	if len(split_duration) == 2:
		hours = 0
开发者ID:SpideRaY,项目名称:strava-uploader,代码行数:33,代码来源:uploader.py


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