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


Python Client.upload_activity方法代码示例

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


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

示例1: upload_files

# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import upload_activity [as 别名]
    def upload_files(self, files):
        """
        Upload files to Strava
        """

        # connect to Strava API
        client = Client(self.config.strava["access_token"])

        for fn in files:

            try:
                upload = client.upload_activity(open(self.src_path + fn, "r"),
                                                "fit")

                activity = upload.wait(30, 10)

                # if a file has been uploaded, copy it locally, as this ensures
                # we don't attempt to re-upload the same activity in future
                if activity:
                    shutil.copy(self.src_path + fn, self.dest_path + fn)
                    logging.debug("new file uploaded: {0}, {1} ({2})".format(
                                  activity.name, activity.distance, fn))

            except exc.ActivityUploadFailed as error:
                print error
开发者ID:thegingerbloke,项目名称:pi-python-garmin-strava,代码行数:27,代码来源:uploader.py

示例2: main

# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import upload_activity [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: activity_translator

# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import upload_activity [as 别名]
		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)
开发者ID:SpideRaY,项目名称:strava-uploader,代码行数:32,代码来源:uploader.py

示例4: print

# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import upload_activity [as 别名]
      # Need to convert sport type into Strava one
      i = 0
      Strava_Sports = model.Activity.TYPES
      if Debug: print("Try to find activity in Strava Sports...")
      while i < len(Strava_Sports):
          if not tcxSportType.find(Strava_Sports[i]) == -1:
              tcxSportType = Strava_Sports[i]
          i = i + 1
          if Debug: print("At {}/{}".format(i,len(Strava_Sports)))
 
      # Next: upload to Strava
      print("Uploading...")
      try:
         upload = StravaClient.upload_activity(
                     activity_file = open(File, 'r'),
                     data_type = 'tcx',
                     private = True if tcxSportType == 'Swim' else False,
                     activity_type = tcxSportType
                     )
      except exc.ActivityUploadFailed as err:
          print("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'):
	     print("Remove dulicate activity file {}".format(File))
	     os.remove(File)
	     isDuplicate = True
	  else:
             exit(1)

      except ConnectionError as err:
          print("No Internet connection: {}".format(err))
开发者ID:nah-ko,项目名称:myStravaTCXPush,代码行数:34,代码来源:pushStrava.py

示例5: print

# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import upload_activity [as 别名]
            nametag, desctag = x.find("{*}name"), x.find("{*}desc")
            title = nametag and nametag.text
            desc = desctag and desctag.text
        elif ext.lower()=='.tcx':
            x = etree.parse(uf)
            notestag = x.find("{*}Activities/{*}Activity/{*}Notes")
            if notestag is not None:
                title, desc = (notestag.text.split('\n',1)+[None])[:2]
    else:
        title = args.title
        desc = args.description

    # upload activity
    try:
        cf.seek(0, 0)
        upstat = client.upload_activity(cf, ext[1:] + '.gz', title, desc, private=args.private, activity_type=args.activity_type)
        activity = upstat.wait()
        duplicate = False
    except exc.ActivityUploadFailed as e:
        words = e.args[0].split()
        if words[-4:-1]==['duplicate','of','activity']:
            activity = client.get_activity(words[-1])
            duplicate = True
        else:
            raise

    # show results
    uri = "http://strava.com/activities/{:d}".format(activity.id)
    print("  {}{}".format(uri, " (duplicate)" if duplicate else ''), file=stderr)
    if not args.no_popup:
        webbrowser.open_new_tab(uri)
开发者ID:grigory-rechistov,项目名称:stravacli,代码行数:33,代码来源:stravaup.py


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