本文整理汇总了Python中fitbit.Fitbit类的典型用法代码示例。如果您正苦于以下问题:Python Fitbit类的具体用法?Python Fitbit怎么用?Python Fitbit使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Fitbit类的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_recent_activities
def test_recent_activities(self):
user_id = "LukeSkywalker"
with mock.patch("fitbit.api.Fitbit.activity_stats") as act_stats:
fb = Fitbit("x", "y")
retval = fb.recent_activities(user_id=user_id)
args, kwargs = act_stats.call_args
self.assertEqual((), args)
self.assertEqual({"user_id": user_id, "qualifier": "recent"}, kwargs)
示例2: test_delete_water
def test_delete_water(self):
log_id = "fake_log_id"
# We need to mock _DELETE_COLLECTION_RESOURCE before we create the Fitbit object,
# since the __init__ is going to set up references to it
with mock.patch("fitbit.api.Fitbit._DELETE_COLLECTION_RESOURCE") as delete_resource:
delete_resource.return_value = 999
fb = Fitbit("x", "y")
retval = fb.delete_foods_log(log_id=log_id)
args, kwargs = delete_resource.call_args
self.assertEqual(("foods/log",), args)
self.assertEqual({"log_id": log_id}, kwargs)
self.assertEqual(999, retval)
示例3: test_delete_water
def test_delete_water(self):
log_id = "OmarKhayyam"
# We need to mock _DELETE_COLLECTION_RESOURCE before we create the Fitbit object,
# since the __init__ is going to set up references to it
with mock.patch('fitbit.api.Fitbit._DELETE_COLLECTION_RESOURCE') as delete_resource:
delete_resource.return_value = 999
fb = Fitbit('x', 'y')
retval = fb.delete_foods_log_water(log_id=log_id)
args, kwargs = delete_resource.call_args
self.assertEqual(('foods/log/water',), args)
self.assertEqual({'log_id': log_id}, kwargs)
self.assertEqual(999, retval)
示例4: test_body
def test_body(self):
# Test the first method defined in __init__ to see if it calls
# _COLLECTION_RESOURCE okay - if it does, they should all since
# they're all built the same way
# We need to mock _COLLECTION_RESOURCE before we create the Fitbit object,
# since the __init__ is going to set up references to it
with mock.patch('fitbit.api.Fitbit._COLLECTION_RESOURCE') as coll_resource:
coll_resource.return_value = 999
fb = Fitbit('x', 'y')
retval = fb.body(date=1, user_id=2, data=3)
args, kwargs = coll_resource.call_args
self.assertEqual(('body',), args)
self.assertEqual({'date': 1, 'user_id': 2, 'data': 3}, kwargs)
self.assertEqual(999, retval)
示例5: render
def render(self, request):
logging.info("Fitbit App, request args: {0}".format(request.args))
# if "init" in request.args:
# self.indx = IndxClient("http://{0}".format(request.args['host'][0]), request.args['box'], request.args['username'], request.args["password"], "FitbitConnector")
# print self.indx
# logging.info("Fitbit App, connected to the box {0}".format(box))
# self.return_ok(request, data = {"init": "ok"})
if "gotourl" in request.args:
gotourl = self.fitbit.get_token_url()
logging.info("Fitbit App, the gotourl is {0}".format(gotourl))
self.return_ok(request, data = {"url": gotourl})
elif "pin" in request.args:
pin = request.args['pin'][0]
logging.info("Fitbit App, the pin is {0}".format(pin))
token = self.fitbit.get_token_with_pin(pin)
self.return_ok(request, data = {"token": json.dumps({"token_key": "{0}".format(token.key), "token_secret": "{0}".format(token.secret)})})
elif "token" in request.args:
token = json.loads(request.args["token"][0])
self.fitbit = Fitbit(self.consumer_key, self.consumer_secret, token['token_key'], token['token_secret'])
self.return_ok(request, data={})
elif "download" in request.args:
self.fitbit_min = FitbitIntraDay(self.fitbit)
start = None
if ("start" in request.args):
start = datetime.fromtimestamp(int(request.args["start"][0])/1000)
response = self.download_data(start)
self.return_ok(request, data = response)
else:
logging.info("Fitbit App, returning 404")
self.return_not_found(request)
return NOT_DONE_YET
示例6: test_auto_refresh_token_exception
def test_auto_refresh_token_exception(self):
"""Test of auto_refresh with Unauthorized exception"""
# 1. first call to _request causes a HTTPUnauthorized
# 2. the token_refresh call is faked
# 3. the second call to _request returns a valid value
refresh_cb = mock.MagicMock()
kwargs = copy.copy(self.client_kwargs)
kwargs.update({
'access_token': 'fake_access_token',
'refresh_token': 'fake_refresh_token',
'refresh_cb': refresh_cb,
})
fb = Fitbit(**kwargs)
profile_url = Fitbit.API_ENDPOINT + '/1/user/-/profile.json'
with requests_mock.mock() as m:
m.get(profile_url, [{
'text': json.dumps({
"errors": [{
"errorType": "expired_token",
"message": "Access token expired:"
}]
}),
'status_code': 401
}, {
'text': '{"user":{"aboutMe": "python-fitbit developer"}}',
'status_code': 200
}])
token = {
'access_token': 'fake_return_access_token',
'refresh_token': 'fake_return_refresh_token'
}
m.post(fb.client.refresh_token_url, text=json.dumps(token))
retval = fb.make_request(profile_url)
self.assertEqual(m.request_history[1].path, '/oauth2/token')
self.assertEqual(
m.request_history[1].headers['Authorization'],
_basic_auth_str(
self.client_kwargs['client_id'],
self.client_kwargs['client_secret']
)
)
self.assertEqual(retval['user']['aboutMe'], "python-fitbit developer")
self.assertEqual("fake_return_access_token", token['access_token'])
self.assertEqual("fake_return_refresh_token", token['refresh_token'])
refresh_cb.assert_called_once_with(token)
示例7: test_too_many_requests
def test_too_many_requests(self):
"""
Tests the 429 response, given in case of exceeding the rate limit
"""
r = mock.Mock(spec=requests.Response)
r.content = b"{'normal': 'resource'}"
r.headers = {'Retry-After': '10'}
f = Fitbit(**self.client_kwargs)
f.client._request = lambda *args, **kwargs: r
r.status_code = 429
try:
f.user_profile_get()
self.assertEqual(True, False) # Won't run if an exception's raised
except exceptions.HTTPTooManyRequests:
e = sys.exc_info()[1]
self.assertEqual(e.retry_after_secs, 10)
示例8: __init__
def __init__(self):
log_handler = logging.FileHandler("fitbit_harvester.log", "a")
log_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(name)s\t%(levelname)s\t%(asctime)s\t%(message)s')
log_handler.setFormatter(formatter)
self.logger = logging.getLogger()
self.logger.setLevel(logging.DEBUG)
for handler in self.logger.handlers: # remove default handler
self.logger.removeHandler(handler)
self.logger.addHandler(log_handler)
data_root = keyring.util.platform_.data_root()
if not os.path.exists(data_root):
os.mkdir(data_root)
keyring.set_keyring(PlaintextKeyring())
self.parser = argparse.ArgumentParser(prog="run")
self.parser.add_argument('--config', help="Set config (input requires JSON) and exit.")
self.parser.add_argument('--get-config', action="store_true", help="Output current config as JSON and exit.")
self.parser.add_argument('--server', help="The server URL to connect to.")
# init fitbit
consumer_key = "9cc7928d03fa4e1a92eda0d01ede2297"
consumer_secret = "340ea36a974e47738a335c0cccfe1fcf"
self.fitbit = Fitbit(consumer_key, consumer_secret)
self.fitbit_intraday = None
self.box_version = 0
self.config_overwrite = False;
self.config_start = self.today()
self.config_box = None
self.config_indx_user = None
self.config_indx_pass = None
self.config_fetched_days = []
self.config_zeros_from = self.today()
self.harvester_id = "fitbit_harvester"
self.steps_ts_id = "fitbit_steps_ts"
self.calories_ts_id = "fitbit_calories_ts"
self.distance_ts_id = "fitbit_distance_ts"
self.floors_ts_id = "fitbit_floors_ts"
self.elevation_ts_id = "fitbit_elevation_ts"
self.ts_count = 0
self.ts_error = None
示例9: test_response_ok
def test_response_ok(self):
"""
This mocks a pretty normal resource, that the request was authenticated,
and data was returned. This test should just run and not raise any
exceptions
"""
r = mock.Mock(spec=requests.Response)
r.status_code = 200
r.content = b'{"normal": "resource"}'
f = Fitbit(**self.client_kwargs)
f.client._request = lambda *args, **kwargs: r
f.user_profile_get()
r.status_code = 202
f.user_profile_get()
r.status_code = 204
f.user_profile_get()
示例10: __init__
def __init__(self, server):
BaseHandler.__init__(self, server)
self.isLeaf = True
self.consumer_key = "9cc7928d03fa4e1a92eda0d01ede2297"
self.consumer_secret = "340ea36a974e47738a335c0cccfe1fcf"
self.fitbit = Fitbit(self.consumer_key, self.consumer_secret)
示例11: IndxClient
# if args['debug']:
# logging.basicConfig(level = logging.DEBUG)
# else:
# logging.basicConfig(level=logging.INFO)
# set up connection to INDX
# password = getpass.getpass()
# indx = IndxClient(args['address'], args['box'], args['user'], args['passwd'], "Fitbit Connector")
# set up connection to Fitbit
consumer_key = "9cc7928d03fa4e1a92eda0d01ede2297"
consumer_secret = "340ea36a974e47738a335c0cccfe1fcf"
# fitbit = Fitbit(consumer_key, consumer_secret, access_token_key, access_token_secret)
fitbit = Fitbit(consumer_key, consumer_secret)
if fitbit.token == None:
gotourl = fitbit.get_token_url()
pin = raw_input("Please input you PIN: ")
fitbit.get_token_with_pin(pin)
fitbit_min = FitbitIntraDay(fitbit)
# def get_fitbit_data():
# from_date = args['from_date']
# to_date = args['to_date']
# print '\nget activities tracker steps:\n'
# return fitbit_ts.get_activities_tracker_steps(to_date, from_date)
def transform_fitbit_response(response):
示例12: FitbitApp
class FitbitApp(BaseHandler):
def __init__(self, server):
BaseHandler.__init__(self, server)
self.isLeaf = True
self.consumer_key = "9cc7928d03fa4e1a92eda0d01ede2297"
self.consumer_secret = "340ea36a974e47738a335c0cccfe1fcf"
self.fitbit = Fitbit(self.consumer_key, self.consumer_secret)
def render(self, request):
logging.info("Fitbit App, request args: {0}".format(request.args))
# if "init" in request.args:
# self.indx = IndxClient("http://{0}".format(request.args['host'][0]), request.args['box'], request.args['username'], request.args["password"], "FitbitConnector")
# print self.indx
# logging.info("Fitbit App, connected to the box {0}".format(box))
# self.return_ok(request, data = {"init": "ok"})
if "gotourl" in request.args:
gotourl = self.fitbit.get_token_url()
logging.info("Fitbit App, the gotourl is {0}".format(gotourl))
self.return_ok(request, data = {"url": gotourl})
elif "pin" in request.args:
pin = request.args['pin'][0]
logging.info("Fitbit App, the pin is {0}".format(pin))
token = self.fitbit.get_token_with_pin(pin)
self.return_ok(request, data = {"token": json.dumps({"token_key": "{0}".format(token.key), "token_secret": "{0}".format(token.secret)})})
elif "token" in request.args:
token = json.loads(request.args["token"][0])
self.fitbit = Fitbit(self.consumer_key, self.consumer_secret, token['token_key'], token['token_secret'])
self.return_ok(request, data={})
elif "download" in request.args:
self.fitbit_min = FitbitIntraDay(self.fitbit)
start = None
if ("start" in request.args):
start = datetime.fromtimestamp(int(request.args["start"][0])/1000)
response = self.download_data(start)
self.return_ok(request, data = response)
else:
logging.info("Fitbit App, returning 404")
self.return_not_found(request)
return NOT_DONE_YET
def download_data(self, start):
# end time is end of yesterday
end = datetime.combine((datetime.now()+timedelta(days=-1)).date(), time(23,59,59))
response = {}
if (start == None):
d = timedelta(days=0)
start = datetime.combine(end.date()+d, time(0,0,0))
response["from_date"] = start.isoformat()
steps = self.fitbit_min.get_steps(start, end)
calories = self.fitbit_min.get_calories(start, end)
distance = self.fitbit_min.get_distance(start, end)
floors = self.fitbit_min.get_floors(start, end)
elevation = self.fitbit_min.get_elevation(start, end)
compact_steps = self.compact_data(steps)
compact_calories = self.compact_data(calories)
compact_distance = self.compact_data(distance)
compact_floors = self.compact_data(floors)
compact_elevation = self.compact_data(elevation)
observations = self.create_observation_points({"step_count":compact_steps, "calories_burned": compact_calories, "distance": compact_distance, "floors_climbed": compact_floors, "elevation": compact_elevation})
response["up_to_date"] = end.isoformat()
response["observations"] = "{0}".format(json.dumps(observations))
return response
def compact_data(self, observations):
out = {}
for day_data in observations:
out = dict(out.items() + self.compact_day_data(day_data).items())
return out
def compact_day_data(self, observations):
out = {}
day = None
for key in observations.keys():
if (not key.endswith('-intraday')):
day = datetime.strptime(observations[key][0]["dateTime"], "%Y-%m-%d").date()
for key in observations.keys():
if (key.endswith('-intraday')):
for obs in observations[key]["dataset"]:
if (obs["value"] != 0):
t = datetime.strptime(obs["time"], "%H:%M:%S").time()
out[datetime.combine(day, t)] = obs["value"]
return out
def create_observation_points(self, lists):
data_points = {}
for key in lists.keys():
lst = lists[key]
for d in lst.keys():
if (d in data_points):
data_points[d] = dict(data_points[d].items() + {key: lst[d]}.items())
else:
data_points[d] = {key: lst[d]}
observations = []
for data_point in data_points.items():
obs = self.create_observation_point(data_point[0], data_point[1])
observations.append(obs)
#.........这里部分代码省略.........
示例13: index
def index():
if 'fitbit_access_token' not in session:
return redirect(url_for('login'))
client = Fitbit(CONSUMER_KEY, CONSUMER_SECRET, resource_owner_key=session['fitbit_access_token']['oauth_token'], resource_owner_secret=session['fitbit_access_token']['oauth_token_secret'])
return str(client.user_profile_get())