本文整理汇总了Python中stravalib.client.Client.get_activities方法的典型用法代码示例。如果您正苦于以下问题:Python Client.get_activities方法的具体用法?Python Client.get_activities怎么用?Python Client.get_activities使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类stravalib.client.Client
的用法示例。
在下文中一共展示了Client.get_activities方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_runs
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import get_activities [as 别名]
def get_runs(request, n):
""" Get most recent n runs associated with an account.
"""
# Our admin object
admin = _get_admin(request)
# Be sure it exists
if not admin.exists_document('strava_access_token'):
request.response.status_int = 403
return
# Get the access token
access_token = admin.get_document('strava_access_token')
running_docs = {
a:admin.get_document(a) for a in admin.list_documents() if a.startswith('run_')
}
strava_client = StravaClient(access_token=access_token['strava_access_token'])
runs = []
for a in strava_client.get_activities():
if 'run_' + str(a.id) in running_docs:
run = running_docs['run_' + str(a.id)]
else:
run = {
'id': a.id,
'timestamp': a.start_date_local.isoformat(),
'duration': a.elapsed_time.total_seconds(),
'distance': unithelper.miles(a.distance).num,
'name': a.name,
'description': a.description
}
if a.map.summary_polyline is not None:
run['map_polyline'] = a.map.summary_polyline
if a.start_latlng is not None and a.start_date is not None and 'darksky' in request.registry.settings['secrets']:
fio = ForecastIO.ForecastIO(
request.registry.settings['secrets']['darksky']['darksky_secret'],
units=ForecastIO.ForecastIO.UNITS_US,
latitude=float(a.start_latlng[0]),
longitude=float(a.start_latlng[1]),
time=str(int(time.mktime(a.start_date.timetuple())))
)
if fio.has_currently():
currently = FIOCurrently.FIOCurrently(fio)
run['temperature'] = currently.temperature
run['weather_icon'] = currently.icon
admin.create_document(run, doc_id='run_' + str(a.id))
runs.append(run)
if n is not None and len(runs) == n:
break
# Return appropriately
request.response.status_int = 200
return {
'runs':
runs
}
示例2: freshness
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import get_activities [as 别名]
def freshness():
c = Client(access_token=session['token'])
try:
limit = int(request.args.get("limit"))
except (TypeError, ValueError):
limit = None
activities = list(c.get_activities(limit=limit))
date = activities[-1].start_date.date()
dates = []
week_vals = []
month_vals = []
while date <= datetime.datetime.now().date():
dates.append(datetime.datetime.combine(date, datetime.datetime.min.time()))
min_week_date = date - datetime.timedelta(days=7)
min_month_date = date - datetime.timedelta(days=30)
M_PER_MILE = 1609
week_vals.append(sum(float(a.distance) / M_PER_MILE for a in activities if a.start_date.date() <= date and a.start_date.date() > min_week_date))
month_vals.append((7 / 30.0) * sum(float(a.distance) / M_PER_MILE for a in activities if a.start_date.date() <= date and a.start_date.date() > min_month_date))
date += datetime.timedelta(days=1)
data = [dates, week_vals, month_vals]
return render_template('freshness.html', data=data)
示例3: authorized
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import get_activities [as 别名]
def authorized():
# get access token to make requests
client = Client()
code = request.args.get('code')
client.access_token = client.exchange_code_for_token(client_id=creds.client_id, client_secret=creds.client_secret, code=code) # add id and secret
# get data
today = datetime.datetime.strptime(str(datetime.date.today()), "%Y-%m-%d")
one_month_ago = today - dateutil.relativedelta.relativedelta(months=1)
athlete = client.get_athlete()
activities = client.get_activities(after=one_month_ago)
rides = toolkit.get_activity_types(activities, 'ride')
runs = toolkit.get_activity_types(activities, 'run')
ride_set = ActivitySet("Rides", rides)
run_set = ActivitySet("Runs", runs)
return render_template('main.html', athlete=athlete, activity_sets=[ride_set, run_set])
示例4: mileage
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import get_activities [as 别名]
def mileage():
c = Client(access_token=session["token"])
limit = int(request.args.get("limit", 200))
activity_models = list(c.get_activities(limit=limit))
activities = []
for a in activity_models:
activities.append({
"name": a.name,
"distance": float(a.distance),
"time": a.moving_time.seconds,
"type": a.type,
"date": a.start_date.isoformat(),
"day": a.start_date.weekday()
})
data = json.dumps(activities)
return render_template('mileage.html', data=data)
示例5: fitness
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import get_activities [as 别名]
def fitness():
c = Client(access_token=session["token"])
try:
limit = int(request.args.get("limit"))
except (TypeError, ValueError):
limit = None
try:
smooth = int(request.args.get("smooth")) / 2
except (ValueError, TypeError):
smooth = 3
activities = list(c.get_activities(limit=limit))
# Bit of a mess. Long run is 2. Old activities are 0, new activities are None
ALLOWED_ACTIVITIES = [None, 0, 2, u"0", u"2"]
activities = list(reversed([a for a in activities if a.average_heartrate and a.workout_type in ALLOWED_ACTIVITIES and a.type == "Run"]))
activities = [a for a in activities if a.average_heartrate > 100 and 1000 * float(a.average_speed) / (a.average_heartrate - 60) < 80] # Sanity for me
vals = [1000 * float(a.average_speed) / (a.average_heartrate - 60) for a in activities]
names = ["{} {}".format(a.name, a.start_date) for a in activities]
smoothed_vals = []
for index, val in enumerate(vals):
slice = vals[max(0, index-smooth):index+smooth+1]
smoothed_vals.append(sum(slice) / (0.0 + len(slice)))
vals_and_dist = [(1000 * float(a.average_speed) / (a.average_heartrate - 60), float(a.distance)) for a in activities]
dist_smoothed_vals = []
for index, val in enumerate(vals):
slice = vals_and_dist[max(0, index-smooth):index+smooth+1]
tot = 0
dist = 0
for run in slice:
tot += run[0] * run[1]
dist += run[1]
dist_smoothed_vals.append(tot / float(dist))
data = [names, vals, smoothed_vals, dist_smoothed_vals]
return render_template('fitness.html', data=data)
示例6: _get_athlete_summary
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import get_activities [as 别名]
def _get_athlete_summary(self, athlete_id):
""" Get a total activity time per athlete. """
tokens = self._get_authed_athletes()
if athlete_id in tokens:
times = []
client = Client(access_token=tokens.get(athlete_id))
activities = client.get_activities(
after=_get_start_date(self.request),
before=_get_end_date(self.request, include_full_day=True),
)
for activity in activities:
times.append(activity.moving_time)
total = datetime.timedelta()
for time in times:
total += time
else:
total = None
return total
示例7: print
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import get_activities [as 别名]
if(REAUTH):
AccessToken = client.exchange_code_for_token(client_id=ClientId,
client_secret=ClientSecret,
code=clientCode)
print(AccessToken)
client = Client(access_token=AccessToken)
athlete = client.get_athlete()
r = open('data.json', 'r')
data = json.load(r)
activities = list(d["id"] for d in data)
r.close()
stravaActivities = client.get_activities()
for activity in stravaActivities:
if (activity.id in activities):
print("Already have this activity!")
continue
a = client.get_activity(activity.id)
if (a.type != "Run"):
print("Activity was a run")
continue
print("Found a new activity!", activity.id)
act = {}
act["date"] = a.start_date_local.strftime("%y-%m-%d")
act["id"] = a.id
act["distance"] = unithelper.miles(a.distance).num
act["duration"] = a.moving_time.seconds
示例8: data_scraper
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import get_activities [as 别名]
def data_scraper(date_end, date_start, athletes=None):
meters_to_miles = 0.000621371
meters_to_feet = 3.28084
km_to_miles = 0.621371
if athletes:
athlete_list = athlete.objects.filter(id=athletes)
else:
athlete_list = athlete.objects.all() # get list of all athletes
for each_athlete in athlete_list: # for each athlete
client = Client(access_token=each_athlete.access_token)
this_athlete_activities = client.get_activities(date_end, date_start) # get list of activities for this month
relevant_existing_activities = [this.id for this in activity.objects.filter(athlete_id=each_athlete).filter(start_date_local__lte=date_end).filter(start_date_local__gte=date_start)]
# print(relevant_existing_activities)
# print(each_athlete, this_athlete_activities)
for each_activity in this_athlete_activities: # for each activity
if not activity.objects.filter(pk=each_activity.id):# check if its already in the database
new_activity = activity(
id=each_activity.id,
athlete_id=athlete.objects.filter(pk=each_activity.athlete.id)[0],
name=each_activity.name,
distance=meters_to_miles*each_activity.distance,
moving_time=each_activity.moving_time,
elapsed_time=each_activity.elapsed_time,
total_elevation_gain=meters_to_feet*each_activity.total_elevation_gain,
type=each_activity.type,
start_date_local=utc.localize(each_activity.start_date_local).astimezone(pst),
average_speed=km_to_miles*each_activity.average_speed,
calories=each_activity.calories,
day=each_activity.start_date_local.day)# if its not in the database, add it
new_activity.save()
get_activity_photos(client, each_activity.id)
else:
get_activity_photos(client, each_activity.id)
try:
relevant_existing_activities.remove(each_activity.id)
except ValueError:
pass # print("item %d in black hole" % each_activity.id)
for extra_activity in relevant_existing_activities:
print('removing item %d from database since it doesnt exist on strava'%extra_activity)
activity.objects.filter(id=extra_activity).delete()
cum = 0
# for this_activity in activity.objects.filter(athlete_id = each_athlete).order_by('start_date_local'):
for each_day in range(1,(date_end.astimezone(pst)-date_start.astimezone(pst)).days+1):
print(each_athlete, each_day)
this_day = activity.objects.filter(athlete_id = each_athlete).filter(start_date_local__lte=before).filter(start_date_local__gte=after).filter(day=each_day).aggregate(daily_sum = Sum('total_elevation_gain'))
cum += this_day['daily_sum'] or 0
today = month.objects.filter(athlete_id = each_athlete).filter(day = each_day)
if today:
for existing_day in today:
existing_day.cum_elev = cum
existing_day.save()
else:
new_day = month(
athlete_id = each_athlete,
day = each_day,
cum_elev = cum
)
new_day.save()
all_athlete_activities = activity.objects.filter(athlete_id=each_athlete).filter(start_date_local__lte=date_end).filter(start_date_local__gte=date_start).order_by('start_date_local')
cum = 0
for every_activity in all_athlete_activities:
cum += every_activity.total_elevation_gain
every_activity.cumulative_elevation = cum
every_activity.save()
month.objects.filter(day__gt=datetime.now().day).delete()
示例9: Strava
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import get_activities [as 别名]
class Strava(object):
def __init__(self):
self.client_id = current_app.config['STRAVA_CLIENT_ID']
self.client_secret = current_app.config['STRAVA_CLIENT_SECRET']
self.redirect_uri = url_for('strava.confirm_auth', _external=True)
self.client = StravaClient()
self._activity_type = 'ride' # rides or runs
self._activities = None
@property
def activity_type(self):
return self._activity_type
@activity_type.setter
def activity_type(self, value):
self._activity_type = value
self._activities = None
@property
def athlete(self):
return self.client.get_athlete()
@property
def activities(self):
if not self._activities:
# current_year = datetime.datetime.now().year
# after = datetime.datetime(current_year - 2, 12, 25)
self._activities = Activities(self.client.get_activities(), self.activity_type)
return self._activities
@classmethod
def authorization_url(cls):
self = cls()
return self.client.authorization_url(client_id=self.client_id,
redirect_uri=self.redirect_uri)
def get_access_token(self, code):
return self.client.exchange_code_for_token(client_id=self.client_id,
client_secret=self.client_secret,
code=code)
@classmethod
def athlete_by_code(cls, code):
self = cls()
self.client.access_token = self.get_access_token(code)
return self.athlete
@classmethod
def athlete_by_token(cls, token):
self = cls()
self.client.access_token = token
return self.athlete
@classmethod
def activities_by_token(cls, token):
self = cls()
self.client.access_token = token
return self.activities
@classmethod
def by_token(cls, token):
self = cls()
self.client.access_token = token
return self
示例10: data_scraper
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import get_activities [as 别名]
def data_scraper(date_start, date_end, athletes=None):
meters_to_miles = 0.000621371
meters_to_feet = 3.28084
km_to_miles = 0.621371
if athletes:
athlete_list = athlete.objects.filter(id=athletes)
else:
athlete_list = athlete.objects.all() # get list of all athletes
for each_athlete in athlete_list: # for each athlete
# try:
client = Client(access_token=each_athlete.access_token)
this_athlete_activities = client.get_activities(date_end, date_start) # get list of activities for this month
relevant_existing_activities = [this.id for this in activity.objects.filter(athlete_id=each_athlete).filter(start_date_local__lte=date_end).filter(start_date_local__gte=date_start)]
# print(relevant_existing_activities)
print(each_athlete, len(relevant_existing_activities))
try:
for each_activity in this_athlete_activities: # for each activity
if not activity.objects.filter(pk=each_activity.id):# check if its already in the database
new_activity = activity(
id=each_activity.id,
athlete_id=athlete.objects.filter(pk=each_activity.athlete.id)[0],
name=each_activity.name[0:139],
distance=meters_to_miles*each_activity.distance,
moving_time=each_activity.moving_time,
elapsed_time=each_activity.elapsed_time,
total_elevation_gain=meters_to_feet*each_activity.total_elevation_gain,
type=each_activity.type,
start_date_local=pst.localize(each_activity.start_date_local),
average_speed=km_to_miles*each_activity.average_speed,
calories=each_activity.calories,
day=each_activity.start_date_local.day)# if its not in the database, add it
new_activity.save()
get_activity_photos(client, each_activity.id)
else:
get_activity_photos(client, each_activity.id)
try:
relevant_existing_activities.remove(each_activity.id)
except ValueError:
pass # print("item %d in black hole" % each_activity.id)
for extra_activity in relevant_existing_activities:
print('removing item %d from database since it doesnt exist on strava'%extra_activity)
activity.objects.filter(id=extra_activity).delete()
except:
print("Not Authorized: " + each_athlete.firstname + " " + each_athlete.lastname)
cum = 0
# for this_activity in activity.objects.filter(athlete_id = each_athlete).order_by('start_date_local'):
if date_end.astimezone(pst) > utc.localize(datetime.utcnow()).astimezone(pst):
end_date = utc.localize(datetime.utcnow()).astimezone(pst)
else:
end_date = date_end.astimezone(pst)
for each_day in range(1,(end_date.astimezone(pst)-date_start.astimezone(pst)).days):
this_day = activity.objects.filter(athlete_id = each_athlete).filter(start_date_local__lte=before).filter(start_date_local__gte=after).filter(day=each_day).aggregate(daily_sum = Sum('total_elevation_gain'))
cum += this_day['daily_sum'] or 0
today = month.objects.filter(athlete_id = each_athlete).filter(day = each_day)
if today:
for existing_day in today:
existing_day.cum_elev = cum
existing_day.save()
else:
new_day = month(
athlete_id = each_athlete,
day = each_day,
cum_elev = cum
)
new_day.save()
all_athlete_activities = activity.objects.filter(athlete_id=each_athlete).filter(start_date_local__lte=date_end).filter(start_date_local__gte=date_start).order_by('start_date_local')
cum = 0
for every_activity in all_athlete_activities:
cum += every_activity.total_elevation_gain
every_activity.cumulative_elevation = cum
every_activity.save()
# month.objects.filter(day__gt=datetime.now().day + 1).delete()
# except:
# print("Not Authorized: " + each_athlete.firstname + " " + each_athlete.lastname)
# update the info for the types pie chart
# find all the types
types = activity.objects.values('type').distinct()
elevation_by_type = activity.objects.filter(start_date_local__lte=before).filter(start_date_local__gte=after).values('type').annotate(Sum('total_elevation_gain'))
distance_by_type = activity.objects.filter(start_date_local__lte=before).filter(start_date_local__gte=after).values('type').annotate(Sum('distance'))
quantity_by_type = activity.objects.filter(start_date_local__lte=before).filter(start_date_local__gte=after).values('type').annotate(Count('id'))
# for each type
for each_value in types:
each_type = each_value['type']
# check to see if it already exists
this_type = activity_type.objects.filter(pk=each_type)
if not this_type:
new_type = activity_type(type = each_type)
new_type.save()
else:
clear = this_type[0]
print("Clearing: %s" % clear)
clear.elevation = 0
clear.save()
for each_item in elevation_by_type:
this_type = activity_type.objects.filter(pk=each_item['type'])[0]
this_type.elevation = each_item['total_elevation_gain__sum']
this_type.save()
for each_item in distance_by_type:
this_type = activity_type.objects.filter(pk=each_item['type'])[0]
#.........这里部分代码省略.........
示例11: Client
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import get_activities [as 别名]
from stravalib.client import Client
club_id = 24151
client = Client(access_token='250d33ceabfbe833376eb18885e797af14888512')
athlete = client.get_athlete() # Get John's full athlete record
print("Hello, {}. I know your email is {}".format(athlete.firstname, athlete.email))
# "Hello, John. I know your email is [email protected]"
activities = client.get_activities(limit=10)
assert len(list(activities)) == 10
clubs = client.get_athlete_clubs()
icc_members = client.get_club_members(club_id, limit=20)
assert len(list(icc_members)) == 20
club_activities = client.get_club_activities(club_id, limit=20)
assert len(list(club_activities)) == 20
#View activities
#for x in activities:
# print (x)
for x in clubs:
print (x)
for x in icc_members:
print (x)
示例12: Client
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import get_activities [as 别名]
from stravalib.client import Client
from stravalib import unithelper
client = Client()
# The access token is the final result from OAuth
client.access_token = ''
athlete = client.get_athlete()
activities = client.get_activities()
activity_list = list(activities)
total_activities = len(activity_list)
print("Total activities retrieved: {total}".format(total=total_activities))
def createTimestamp(ts): # creating timestamp string from timestamp object
return '{year}-{month}-{day} {hour}:{minute}:{second}'.format(year=ts.year, month=ts.month, day=ts.day, hour=ts.hour, minute=ts.minute, second=ts.second)
def xstr(s):
if s is None:
return ''
else:
return str(s)
print 'Opening file to write...'
outputfile = open('runLogsSorted.csv', 'a') # Append the entry for each run to this file
schema = '"ID","Name","Distance (mi)","Moving time (s)","Elapsed time (s)","Elevation gain (ft)","Avg speed (mph)","Max speed (mph)","Avg cadence","Avg temp (C)","Avg HR","Max HR","Calories","Shoes","Start timestamp (local)","Start Lat","Start Lng","End Lat","End Lng","City","State","Country","Achievements","Kudos","Workout type"\n'
print 'Writing schema...'
示例13: get_client_activities
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import get_activities [as 别名]
def get_client_activities(access_token, limit):
client = Client(access_token=ACCESS_TOKEN)
activities = client.get_activities(limit=limit)
return activities
示例14: Client
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import get_activities [as 别名]
from stravalib import unithelper
client_id = os.environ.get('STRAVA_CLIENT_ID', None)
client_secret = os.environ.get('STRAVA_CLIENT_SECRET', None)
access_token = os.environ.get('STRAVA_ACCESS_TOKEN', None)
if __name__ == '__main__':
mysegments = {}
# get athlete
client = Client(access_token) # 1 -- possibly not counted
athlete = client.get_athlete() # 2
# get athlete activities
activities = client.get_activities(limit=200) # 3
print("number of activities returned", str(len(list(activities))))
# per activity, get segment efforts
for activity in activities:
segment_efforts = client.get_activity(activity.id).segment_efforts # 4
# 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 # 12
# get friend with time < athlete time
示例15: getcwd
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import get_activities [as 别名]
stream_filter = ["latlng", "altitude", "heartrate", "velocity_smooth", "moving", "grade_smooth"]
this_dir = getcwd()
output_dir = join(this_dir, "MAF")
output_detail_dir = join(output_dir, "detail")
from_date = datetime(2016, 2, 27)
if not exists(output_detail_dir):
print "Creating {0}".format(output_detail_dir)
makedirs(output_detail_dir)
# Download some activities
print "Downloading activities from {0:%d %b %Y}".format(from_date)
acts = client.get_activities(after=from_date)
for act in acts:
total += 1
if act.type != "Run" or act.average_heartrate is None:
continue
count += 1
# Get the full data streams
streams = client.get_activity_streams(act.id, types=stream_filter)
sdf = pd.DataFrame(dict((stype, stream.data) for (stype, stream) in streams.iteritems()))
if "latlng" in stream_filter:
sdf["lat"] = [a[0] for a in sdf.latlng]