本文整理汇总了Python中stravalib.Client.get_activities方法的典型用法代码示例。如果您正苦于以下问题:Python Client.get_activities方法的具体用法?Python Client.get_activities怎么用?Python Client.get_activities使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类stravalib.Client
的用法示例。
在下文中一共展示了Client.get_activities方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: process
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activities [as 别名]
def process():
token = session.get('access_token', None)
if token is None:
return redirect(url_for('login'))
client = Client(token)
athlete = client.get_athlete()
activities = client.get_activities()
points = [pnt for a in activities for pnt in (a.end_latlng, a.start_latlng) if pnt]
#temp = [pnt for ints in point_intercepts(points) for pnt in ints]
#temp = filter_close_points(points)
seg = []
for grps in group_points(points):
out = []
for pnt in grps:
out.append("<trkpt lat=\"{0.lat}\" lon=\"{0.lon}\"></trkpt>".format(pnt))
seg.append("<trkseg>{}</trkseg>".format("".join(out)))
return """<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.0">
<name>TEST</name>
<trk>{}</trk>
</gpx>""".format("".join(seg))
return "<html><body><img src='{}'/>{} {}</body></html>".format(athlete.profile, athlete.firstname, athlete.lastname)
示例2: main
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activities [as 别名]
def main():
access_token = getToken()
if access_token == None:
return redirectAuth()
client = Client(access_token=access_token)
athlete = client.get_athlete() # Get current athlete details
#if you want a simple output of first name, last name, just use this line:
#return athlete.firstname + ' ' + athlete.lastname
#now get most recent activity for this athlete...
names = []
maps = []
for a in client.get_activities(before = "2016-08-12T00:00:00Z", limit=1):
names.append(a.name)
maps.append(a.map)
# another simple output for this bit is to return the name of the route
#return names[0]
# but a sightly more complicated output is this matplotlib figure --
m = maps[0]
summary_lat_lon = polyline.decode(m.summary_polyline)
lats = [i[0] for i in summary_lat_lon]
lons = [i[1] for i in summary_lat_lon]
session['name']=names[0]
session['lats']=lats
session['lons']=lons
return redirect('/simple.png')
示例3: get_activity_map
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activities [as 别名]
def get_activity_map():
# just to see if i can plot my own activity map!
f = open('secrets.txt', 'r')
MY_STRAVA_CLIENT_ID = f.readline().strip()
MY_STRAVA_CLIENT_SECRET = f.readline().strip()
STORED_ACCESS_TOKEN = f.readline().strip()
f.close()
from stravalib import Client
client = Client(access_token=STORED_ACCESS_TOKEN)
client.get_athlete(7656735) # Get current athlete details
#now get most recent activity for this athlete...
a=client.get_activities(before = "2016-08-11T00:00:00Z", limit=1)
session['map']=a.map
session['name']=a.name
示例4: process
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activities [as 别名]
def process():
token = session.get('access_token', None)
if token is None:
return redirect(url_for('login'))
client = Client(token)
athlete = client.get_athlete()
activities = client.get_activities()
for a in activities:
if not a.commute and "commute" in a.name.lower():
print(a)
client.update_activity(a.id, commute=True)
return "<html><body>processed</body></html>"
示例5: get_activities_from_strava
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activities [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)
示例6: load_strava_data
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activities [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()
示例7: load_activities
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activities [as 别名]
def load_activities():
users_id = session['athlete']['id']
c = Client(access_token=session['token'])
activities = list(c.get_activities())
cur = g.db.cursor()
# Delete activities before loading to prevent id clashes
cur.execute('delete from activities where users_id = ?', [users_id])
g.db.commit()
# TODO: bulk create
for a in activities:
cur.execute('insert into activities (id, name, distance, start_time, users_id) values (?, ?, ?, ?, ?)',
(a.id, a.name, int(a.distance) / 1609, a.start_date, users_id))
g.db.commit()
cur.close()
return redirect('/activities')
示例8: token
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activities [as 别名]
def token(request):
# Get temporary code after the request
code = request.GET.get("code")
# exchange the code for an access token.
client = Client()
access_token = client.exchange_code_for_token(client_id=STRAVA_CLIENT_ID,
client_secret=STRAVA_CLIENT_SECRET,
code=code)
# Get Athlete
athlete = client.get_athlete()
# See if the athlete exists in our DB
# current_athlete = get_object_or_404(Athlete, id_strava = athlete.id)
# current_athlete = ""
try:
current_athlete = Athlete.objects.get(id_strava = athlete.id)
except (KeyError, Athlete.DoesNotExist):
current_athlete = Athlete(first_name=athlete.firstname, last_name=athlete.lastname, access_token=access_token, id_strava = athlete.id )
current_athlete.save()
# **************************
# Prep content for the HTML page.
# Get Activities.
activities = client.get_activities()
# Make a list of activities to send to the html page. These are all the activities for this athlete.
activity_list = []
name_list = []
for a in activities:
temp = [a.id, a.name, a.distance, a.moving_time, a.elapsed_time, a.start_date_local]
activity_list.append(temp)
# information to send to the html page
context = { 'activity_list': activity_list, 'current_athlete': current_athlete }
template = loader.get_template('shred/activities.html')
return HttpResponse(template.render(context))
示例9: dave
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activities [as 别名]
def dave():
config = configparser.ConfigParser()
config.read(BEE42_INI)
ini_beeminder = config[BEE42_INI_BEEMINDER]
username = ini_beeminder[BEE42_INI_USERNAME]
token = ini_beeminder[BEE42_INI_TOKEN]
strava_token = ini_beeminder[BEE42_INI_STRAVA_TOKEN]
user = User(username, token)
print("Username:", user.username, "tz:", user.timezone, "update:", user.updated_at, "goals", user.goalslugs, "db:", user.deadbeat)
strava_client = Client(access_token=strava_token)
strava_athlete = strava_client.get_athlete()
print(strava_athlete.firstname)
strava_activities = strava_client.get_activities(limit=15)
for a in strava_activities:
if (a.type == "Run"):
print(add_run(user, a))
elif (a.type == "Ride"):
print(add_ride(user, a))
示例10: artbot
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activities [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
示例11: authorization
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activities [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)
#.........这里部分代码省略.........
示例12: massive_test
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activities [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?
示例13: timezone
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activities [as 别名]
debug = False
METERS_IN_A_MILE = 1609.34
pacific_timezone = timezone('America/Los_Angeles')
#mmf = MapMyFitness(api_key=MMF_CLIENT_KEY, access_token=MMF_ACCESS_TOKEN)
strava = Client( access_token=STRAVA_ACCESS_TOKEN)
fitbit_client = fitbit.Fitbit( FITBIT_CLIENT_KEY, FITBIT_CLIENT_SECRET, user_key=FITBIT_USER_KEY, user_secret=FITBIT_USER_SECRET)
# Only grab the last 10 activities
activities = strava.get_activities( limit = 10 )
#for activity in activities:
# print activity.type
# Iterate through all valid activity types
#for activity_id in MMF_BIKE_ACTIVITY_TYPES:
# workouts = workouts + mmf.workout.search( user=MMF_USER_ID, activity_type=activity_id, started_after=started_after )
for activity in activities:
start_datetime = activity.start_date_local
start_date = start_datetime.strftime( '%Y-%m-%d' )
start_time = start_datetime.strftime( '%H:%M' )
duration_milliseconds = int( 1000 * activity.moving_time.total_seconds() )
distance = unithelper.miles( activity.distance ).num
示例14: range
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import get_activities [as 别名]
# My data
my_data = client.get_athlete() # athlete details
me = {}
me["id"] = my_data.id
me["name"] = my_data.firstname + " " + my_data.lastname
me["city"] = my_data.city
my_bikes = my_data.bikes
bikes = {}
for b in my_bikes:
bike = {}
bike[b.id] = b.name
bikes.update(bike)
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":