本文整理汇总了Python中stravalib.Client.get_activity方法的典型用法代码示例。如果您正苦于以下问题:Python Client.get_activity方法的具体用法?Python Client.get_activity怎么用?Python Client.get_activity使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类stravalib.Client
的用法示例。
在下文中一共展示了Client.get_activity方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_activities_from_strava
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activity [as 别名]
def get_activities_from_strava():
last_activity = None
if not os.path.exists(STRAVA_ACCESS_TOKEN_STRING_FNAME):
print '* Obtain a request token ...'
strava_client = Client()
auth_url = strava_client.authorization_url(client_id='601', redirect_uri='http://127.0.0.1:5000/authorisation')
print auth_url
auth_token = strava_client.exchange_code_for_token(client_id='601', client_secret='600580e02b4814c75c93d3a60e15077147895776', code = '74cc257e6bc370d9da44cabc8852f3667ad95515')
print auth_token
# write the access token to file; next time we just read it from file
if DEBUG:
print 'Writing file', STRAVA_ACCESS_TOKEN_STRING_FNAME
fobj = open(STRAVA_ACCESS_TOKEN_STRING_FNAME, 'w')
fobj.write(auth_token)
fobj.close()
else:
if DEBUG:
print 'Reading file', STRAVA_ACCESS_TOKEN_STRING_FNAME
fobj = open(STRAVA_ACCESS_TOKEN_STRING_FNAME)
access_token_string = fobj.read()
print access_token_string
#access_token = oauth.OAuthToken.from_string(access_token_string)
strava_client = Client(access_token=access_token_string)
activities = strava_client.get_activities(limit=10)
# for activity in activities:
# details = strava_client.get_activity(activity_id=activity.id)
# print details.name
# print unithelper.kilometers(details.distance)
# print details.start_date_local
# print details.elapsed_time
# print details.calories
# print details.type
# print "------"
# fobj.close()
for activity in activities:
last_activity = activity
return strava_client.get_activity(activity_id=activity.id)
示例2: load_strava_data
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activity [as 别名]
def load_strava_data(user_id):
user = User.objects.get(id=user_id)
token = user.social_auth.get(provider='strava').tokens
c = StravaClient(token)
# fetch 200 activities
activities = c.get_activities(limit=200)
for track in activities:
activity, created = Activity.objects.get_or_create(
guID=track.id,
user=user
)
print track.id
activity.provider = Activity.STRAVA_PROVIDER
activity.location_city = track.location_city
activity.location_country = track.location_country
full_activity = c.get_activity(track.id)
activity.polyline = full_activity.map.polyline
activity.moving_time = full_activity.moving_time
activity.start_date = full_activity.start_date
activity.distance = float(
unithelper.meters(
track.distance
)
)
activity.total_elevation_gain = float(
unithelper.meters(
track.total_elevation_gain
)
)
activity.resource_state = track.resource_state
activity.description = track.description
if hasattr(track, 'start_latlng') and track.start_latlng is not None:
activity.start_point = Point(
track.start_latlng.lon,
track.start_latlng.lat
)
activity.save()
if activity.polyline:
activity.route = LineString(polyline_decode(activity.polyline))
activity.save()
示例3: artbot
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activity [as 别名]
class artbot(PyBot):
def bot_init(self):
"""
Custom initialization. Specify any configuration options you want to
override, as in particular your OAuth credentials.
"""
#############################
# #
# Twitter OAuth Credentials #
# #
# FILL THESE IN! #
# #
#############################
self.config['api_key'] = 'your_api_key'
self.config['api_secret'] = 'your_api_secret'
self.config['access_key'] = 'your_access_key'
self.config['access_secret'] = 'your_access_secret'
#############################
# #
# Other config options #
# #
# Fill these in if you want #
# or otherwise need to. #
# #
#############################
self.config['strava_access_token'] = 'your_strava_token'
self.config['update_day'] = 0
self.config['update_hour'] = 13
self.config['update_minute'] = 13
self.config['tweet_interval'] = self._compute_interval
# Create the Strava client.
self.client = Client(access_token = self.config['strava_access_token'])
def on_tweet(self):
# First, pull in the stats from Strava.
current = datetime.datetime.now()
last_week = current + datetime.timedelta(weeks = -1)
after = datetime.datetime(last_week.year, last_week.month, last_week.day)
activities = self.client.get_activities(after = after)
# Second, filter by activity type and time frame.
lf = [a for a in activities if a.start_date_local.day != current.day]
num_activities = len(lf)
l = [a.id for a in lf if a.type == 'Run']
# Third, tabulate up the stats for mileage and calories.
mileage = 0.0
calories = 0.0
for activity_id in l:
activity = self.client.get_activity(activity_id)
distance = unithelper.miles(activity.distance)
mileage += round(distance.num, 2) # Rounds to 2 sig figs.
calories += activity.calories
calories = int(calories)
# Finally, use the stats to craft a tweet. This can be any format
# you want, but I'll use the example one from the start of the post.
tweet = "My training last week: {:d} workouts for {:.2f} miles and {:d} calories burned.".format(num_activities, mileage, calories)
self.update_status(tweet)
def _compute_interval(self):
"""
This is a little more sophisticated than the method in the original
blog post. This is to provide for *exactly* specifying when we want
a post to be made, down to the minute.
"""
now = datetime.datetime.now()
target = datetime.datetime(year = now.year, month = now.month, day = now.day,
hour = self.config['update_hour'], minute = self.config['update_minute'])
days_ahead = self.config['update_day'] - now.weekday()
if (days_ahead < 0) or (days_ahead == 0 and (target - now).days < 0):
days_ahead += 7
td = target + datetime.timedelta(days = days_ahead)
interval = int((td - datetime.datetime.now()).total_seconds())
return interval
示例4: map
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activity [as 别名]
def map(request, athlete_id, activity_id):
# athlete_id = athlete_id #421122 #750228
# activity_id = activity_id #577320490 #476912675
path = "../../../../../data/" + format(athlete_id) + "_" + format(activity_id) + ".txt"
file_to_write_to = open(path, "w")
# print(file_to_write_to.path)
writer = csv.writer(file_to_write_to, delimiter=',', quotechar='', quoting=csv.QUOTE_NONE)
#write header row for text file
activity_tuple = "AthleteID", "ActivityID", "StartTime", "TotalElapsedTime", "TotalDistanceMeters", "MaxSpeedMPH", "MeasuredTime", "Latitude", "Longitude", "AltitudeMeters", "DistanceMeters", "current_speedMPH", "CurrentGrade"
writer.writerow(activity_tuple)
# By now the athlete should exist
current_athlete = Athlete.objects.get(id_strava = athlete_id)
# Use the access_token ### "58298d33c3a183c12673691a1ae53d261b08c3a4"
client = Client(access_token=current_athlete.access_token)
#activity id
strava_ride = client.get_activity(activity_id)
# values we are using in calculations and sending to the template
max_speed = format(float(strava_ride.max_speed * 2.23693629), '.9f')
average_speed = format(float(strava_ride.average_speed * 2.23693629), '.9f')
ride_name = strava_ride.name
# Streams
stream_types = "time","distance","latlng","altitude","grade_smooth","velocity_smooth"
streams = client.get_activity_streams(activity_id, types=stream_types)
stream_time = streams["time"].data
stream_distance = streams["distance"].data
stream_lat_lng = streams["latlng"].data
stream_altitude = streams["altitude"].data
stream_grade = streams["grade_smooth"].data
stream_velocity = streams["velocity_smooth"].data
stream_tuple = zip(stream_time, stream_distance, stream_lat_lng, stream_altitude, stream_grade, stream_velocity)
# combined_array is to collect all the values to do some calculations later.
combined_array = []
# combined_string is a string version of the array to send to the template.
combined_string = ""
# Getting info from the streams and combining it all into a CSV format.
for (tTime,tDistance,tLatLng,tAltitude,tGrade,tVelocity) in stream_tuple:
current_time = strava_ride.start_date_local + timedelta(seconds=tTime)
# current_speed = format(float(tVelocity * 2.23693629), '.9f')
current_speed = tVelocity * 2.23693629
activity_tuple = athlete_id, activity_id, strava_ride.start_date_local, strava_ride.elapsed_time, \
float(strava_ride.distance), max_speed, current_time, tLatLng[0], tLatLng[1], \
tAltitude, tDistance, current_speed, tGrade
writer.writerow(activity_tuple)
temp_stuff = []
temp_stuff.append(format(current_time))
temp_stuff.append(format(tLatLng[0]))
temp_stuff.append(format(tLatLng[1]))
temp_stuff.append(format(current_speed))
combined_array.append(temp_stuff)
file_to_write_to.close()
# make special Shred Analytics average speeds that remove all 0 values.
sa_average_speed = 0.0
sa_avg_index = 0
for i in combined_array:
# i[3] is speed
if float(i[3]) > 0.5:
sa_average_speed = sa_average_speed + float(i[3])
sa_avg_index = sa_avg_index + 1
# Make a string version of the arracy to send to Javascript.
combined_string += ','.join(i) + "@"
# the important calculation
sa_average_speed = sa_average_speed / sa_avg_index
context = {'sa_average_speed': sa_average_speed, 'max_speed': max_speed, 'average_speed': average_speed, 'ride_name': ride_name, 'athlete_id': athlete_id, 'activity_id': activity_id, 'start_lat': combined_array[3][1], 'start_lon': combined_array[3][2], 'file_string': combined_string}
template = loader.get_template('shred/map.html')
return HttpResponse(template.render(context))
示例5: compare
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activity [as 别名]
def compare (request):
athlete_id = request.GET.get("athlete_id")
# how do I get what is in the URL?
# I want to send an arbitrary array and get that in the URL
# code = request.GET.get("code") <-- works for one item
# what if the URL is just /compare/runs=123,456,789
# runs = request.GET.get("runs")
# Then split that string into an array...
# use the token URL pattern as a template
# By now the athlete should exist
current_athlete = Athlete.objects.get(id_strava = athlete_id)
# Use the access_token ### "58298d33c3a183c12673691a1ae53d261b08c3a4"
client = Client(access_token=current_athlete.access_token)
# hardcoded sleighride activities.
activities = [547540459, 547545741, 547550929, 559626235]
max_speed = 0.0
ride_names = []
# combined_array is to collect all the values to do some calculations later.
combined_array = []
all_speeds = []
for ac in activities:
#activity id
strava_ride = client.get_activity(ac)
# Get and update the highest maxspeed across rides.
t_max_speed = float(strava_ride.max_speed * 2.23693629)
if t_max_speed > max_speed:
max_speed = t_max_speed
# Add the activity name to this array
ride_names.append(strava_ride.name)
# Streams
stream_types = "time","distance","latlng","altitude","grade_smooth","velocity_smooth"
streams = client.get_activity_streams(strava_ride.id, types=stream_types)
stream_time = streams["time"].data
stream_distance = streams["distance"].data
stream_lat_lng = streams["latlng"].data
stream_altitude = streams["altitude"].data
stream_grade = streams["grade_smooth"].data
stream_velocity = streams["velocity_smooth"].data
stream_tuple = zip(stream_time, stream_distance, stream_lat_lng, stream_altitude, stream_grade, stream_velocity)
# Getting info from the streams and combining it all into a CSV format.
for (tTime,tDistance,tLatLng,tAltitude,tGrade,tVelocity) in stream_tuple:
current_time = strava_ride.start_date_local + timedelta(seconds=tTime)
# current_speed = format(float(tVelocity * 2.23693629), '.9f')
current_speed = tVelocity * 2.23693629
if current_speed > 0.5:
all_speeds.append(current_speed)
temp_stuff = []
temp_stuff.append(format(current_time))
temp_stuff.append(format(tLatLng[0]))
temp_stuff.append(format(tLatLng[1]))
temp_stuff.append(format(current_speed))
combined_array.append(temp_stuff)
# End inner FOR
# insert splitter between runs
combined_array.append(["$$$"])
# END outer FOR
# make special Shred Analytics average speeds that remove all 0 values.
sa_average_speed = mean(all_speeds)
# combined_string is a string version of the array to send to the template.
combined_string = ""
# Make a string version of the arracy to send to Javascript.
for i in combined_array:
combined_string += ','.join(i) + "@"
context = {'sa_average_speed': sa_average_speed, 'max_speed': max_speed, 'ride_names': ride_names, 'start_lat': combined_array[3][1], 'start_lon': combined_array[3][2], 'file_string': combined_string}
template = loader.get_template('shred/compare.html')
return HttpResponse(template.render(context))
示例6: massive_test
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activity [as 别名]
def massive_test(access_token, athlete_id):
client = Client(access_token=access_token)
mysegments = {} # all segments a user has ridden
# get athlete activities
athlete_from_db = Athlete.objects.get(strava_id=athlete_id)
activities = client.get_activities(limit=5, before=athlete_from_db.oldest_activity_date) # API call
# per activity, get segment efforts
for activity in activities:
if activity.type not in ['Ride', 'ride']:
continue
try:
# if activity already exists in db, skip it
Activity.objects.get(strava_id=activity.id)
continue
except Activity.DoesNotExist:
new_activity = Activity()
new_activity.strava_id = activity.id
new_activity.start_lat = activity.start_latitude
new_activity.start_long = activity.start_longitude
new_activity.start_date = activity.start_date
new_activity.save()
# update newest / oldest activity dates
if athlete_from_db.newest_activity_date is None:
athlete_from_db.newest_activity_date = activity.start_date
athlete_from_db.oldest_activity_date = activity.start_date
else:
if activity.start_date > athlete_from_db.newest_activity_date:
athlete_from_db.newest_activity_date = activity.start_date
elif activity.start_date < athlete_from_db.oldest_activity_date:
athlete_from_db.oldest_activity_date = activity.start_date
athlete_from_db.save()
segment_efforts = client.get_activity(activity.id).segment_efforts # API call
# per segment effort
for segment in segment_efforts:
mysegments[segment.segment.id] = segment.segment # save to db
# check if segment leaderboard contains any friends
for key, segment in mysegments.iteritems():
leaderboard = client.get_segment_leaderboard(key, following=True).entries # API call (possibly lots, depends on number of segments)
# get friend with time < athlete time
for i, entry in enumerate(leaderboard):
if entry.athlete_id == athlete_id:
me = entry
if i == 0:
# I'm already the winner!
break
j = 1
while j <= i and leaderboard[i - j].elapsed_time == me.elapsed_time:
# check for ties, compare each entry from i to zero (possibly)
j += 1
if leaderboard[i - j].elapsed_time == me.elapsed_time:
# if they're still tied at the end of the loop, I don't want to see it
break
other = leaderboard[i - j]
try:
new_segment = ChallengedSegment.objects.get(my_id=athlete_id, segment_id=segment.id)
except ChallengedSegment.DoesNotExist:
new_segment = ChallengedSegment()
new_segment.my_id = athlete_id
new_segment.their_id = other.athlete_id
new_segment.their_name = other.athlete_name
new_segment.my_pr = me.activity_id
new_segment.their_pr = other.activity_id
new_segment.my_time = str(me.elapsed_time)
new_segment.their_time = str(other.elapsed_time)
new_segment.difference = str(me.elapsed_time - other.elapsed_time)
new_segment.segment_id = segment.id
new_segment.segment_name = segment.name
new_segment.segment_distance = str(unithelper.miles(segment.distance))
new_segment.save()
break # we already found my entry, why keep looking through the list?
示例7: main
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activity [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)
示例8: range
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activity [as 别名]
me["bikes"] = bikes
# Fetch activities this year
my_activities = client.get_activities(after=datetime(2015, 1, 1)) #(limit=5)
act = []
for a in my_activities:
act.append(a)
# Fetch every activity % make collections
cycling_collection = []
swimming_collection = []
for i in range(len(act)):
print "fetching activity " + str(i)
id = act[i].id
activity = client.get_activity(id)
# Activity collections
if activity.type == "Ride":
my_activity = {}
my_activity["type"] = "cycling"
my_activity["date"] = str(activity.start_date_local)
my_activity["time"] = str(activity.moving_time)
my_activity["distance"] = str(activity.distance)
my_activity["avg_speed"] = str(activity.average_speed)
my_activity["energy"] = str(activity.kilojoules)
cycling_collection.append(my_activity)
elif activity.type == "Swim":
my_activity = {}
my_activity["type"] = "swimming"
my_activity["date"] = str(activity.start_date_local)
示例9: print
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activity [as 别名]
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)