本文整理汇总了Python中stravalib.Client.get_activity_streams方法的典型用法代码示例。如果您正苦于以下问题:Python Client.get_activity_streams方法的具体用法?Python Client.get_activity_streams怎么用?Python Client.get_activity_streams使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类stravalib.Client
的用法示例。
在下文中一共展示了Client.get_activity_streams方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: compare
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activity_streams [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))
示例2: map
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activity_streams [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))
示例3: authorization
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activity_streams [as 别名]
def authorization(request):
client = Client()
code = request.GET['code']
access_token = client.exchange_code_for_token(client_id=MY_STRAVA_CLIENT_ID, client_secret=MY_STRAVA_CLIENT_SECRET, code=code)
# making a global variable to be used across views. don't know how this will work in practice
client = Client(access_token=access_token)
athlete = client.get_athlete() # Get current athlete details
global athleteId
athleteId = athlete.id
# if athlete doesn't exist, add them
if len(Athlete.objects.filter(athleteId=athleteId)) == 0:
ath = Athlete.objects.create(name=str(athlete.firstname+' '+athlete.lastname), athleteId=athleteId, profilePic=athlete.profile, city=athlete.city, country=athlete.country, sex=athlete.sex, premium=athlete.premium, created_at=athlete.created_at, updated_at=athlete.updated_at, followers=athlete.follower_count, friends=athlete.friend_count, email=athlete.email, weight=athlete.weight, meas_pref=athlete.measurement_preference, runsSummary = DataFrame({}).to_json(orient='records'), fitLines = DataFrame({}).to_json(orient='records'), masterList = DataFrame({}).to_json(orient='records'))
ath.profilePic.name = "rudyzPic"
ath.save(update_fields=['profilePic'])
# if athlete already exists, draw their file
elif len(Athlete.objects.filter(athleteId=athleteId)) == 1:
ath = Athlete.objects.get(athleteId=athleteId)
############################################
##### compiling new runs, updating summary
# athlete's existing runs summary
existingSummary = DataFrame(pd.read_json(ath.runsSummary))
existingFitlines = DataFrame(pd.read_json(ath.fitLines))
masterList = DataFrame(pd.read_json(ath.masterList))
activities = list(client.get_activities())
# activity IDs of runs already in the system
try:
ids = existingSummary.activityId
except AttributeError:
ids = []
for i in range(len(activities)):
#for i in range(30,37):
# Ignoring activities already in the system
if (len(ids) == 0) or (float(activities[i].id) not in list(ids)):
try:
# compiling df for raw json-ization
activityId = activities[i].id
run = client.get_activity_streams(activityId, types=['time','latlng','distance','heartrate','altitude','cadence'])
latlng = run['latlng'].data
time = run['time'].data
distance = run['distance'].data
heartrate = run['heartrate'].data
altitude = run['altitude'].data
cadence = run['cadence'].data
date = activities[i].start_date_local
activity = activityId
dfi = thresher.assemble(date, activityId, heartrate, distance, time, altitude, latlng, cadence)
# basic cleanup, only removing totally unreasonable values
dfi = thresher.basicClean(dfi)
# if we ever want to try our hand at improving strava's speed data (ie by predicting speed when GPS blanks), intervene here:
#dfi = thresher.addDistDeltas(dfi)
try:
fitline = thresher.getFitlineLws(dfi) # this adds speed-shifted columns
except:
fitline = pd.DataFrame({})
try:
mafScore = fitline[fitline.hr == 140.0].avgSpeed.iloc[0]
print "MAF "
print mafScore
except:
mafScore = np.nan
fitline_json = fitline.to_json(orient='records')
# getting summary info for run (as one-entry dict)
runSummary = thresher.getSingleSummaryDf(dfi)
# adding mafScore to summary
runSummary['mafScore'] = mafScore
print runSummary
# adding predicted hr and speed values
#dfi = thresher.getPred(dfi)
# saving entry to database
Activity.objects.create(act_id = activityId, name=str(activities[i].name), description=activities[i].description, act_type=activities[i].type, date=activities[i].start_date_local, timezone=activities[i].timezone, df=dfi.to_json(orient='records'), avgHr=runSummary['avgHr'], hrVar=runSummary['variation'], realMiles=runSummary['realMiles'], recovery=runSummary['recovery'], easy=runSummary['easy'], stamina=runSummary['stamina'], impulse=runSummary['impulse'], totalTime=runSummary['totalTime'], totalDist=runSummary['totalDist'], climb=runSummary['climb'], fitline=fitline_json, mafScore=mafScore, athlete=ath)
# updating runs summary
existingSummary = existingSummary.append(runSummary, ignore_index=True)
existingFitlines = existingFitlines.append(fitline, ignore_index=True)
#.........这里部分代码省略.........