本文整理汇总了Python中fitbit.Fitbit方法的典型用法代码示例。如果您正苦于以下问题:Python fitbit.Fitbit方法的具体用法?Python fitbit.Fitbit怎么用?Python fitbit.Fitbit使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类fitbit
的用法示例。
在下文中一共展示了fitbit.Fitbit方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_fitbit
# 需要导入模块: import fitbit [as 别名]
# 或者: from fitbit import Fitbit [as 别名]
def create_fitbit(consumer_key=None, consumer_secret=None, **kwargs):
"""Shortcut to create a Fitbit instance.
If consumer_key or consumer_secret are not provided, then the values
specified in settings are used.
"""
if consumer_key is None:
consumer_key = get_setting('FITBIT_CONSUMER_KEY')
if consumer_secret is None:
consumer_secret = get_setting('FITBIT_CONSUMER_SECRET')
if consumer_key is None or consumer_secret is None:
raise ImproperlyConfigured(
'Consumer key and consumer secret cannot '
'be null, and must be explicitly specified or set in your '
'Django settings'
)
return Fitbit(consumer_key, consumer_secret, **kwargs)
示例2: get_fitbit_data
# 需要导入模块: import fitbit [as 别名]
# 或者: from fitbit import Fitbit [as 别名]
def get_fitbit_data(fbuser, resource_type, base_date=None, period=None,
end_date=None):
"""Creates a Fitbit API instance and retrieves step data for the period.
Several exceptions may be thrown:
TypeError - Either end_date or period must be specified, but
not both.
ValueError - Invalid argument formats.
HTTPUnauthorized - 401 - fbuser has bad authentication credentials.
HTTPForbidden - 403 - This isn't specified by Fitbit, but does
appear in the Python Fitbit library.
HTTPNotFound - 404 - The specific resource doesn't exist.
HTTPConflict - 409 - HTTP conflict
HTTPTooManyRequests - 429 - Hitting the rate limit
HTTPServerError - >=500 - Fitbit server error or maintenance.
HTTPBadRequest - >=400 - Bad request.
"""
fb = create_fitbit(**fbuser.get_user_data())
resource_path = resource_type.path()
data = fb.time_series(resource_path, user_id=fbuser.fitbit_user,
period=period, base_date=base_date,
end_date=end_date)
return data[resource_path.replace('/', '-')]
示例3: get_steps
# 需要导入模块: import fitbit [as 别名]
# 或者: from fitbit import Fitbit [as 别名]
def get_steps():
num_steps = 0
client = fitbit.Fitbit(CONSUMER_KEY,
CONSUMER_SECRET,
access_token=ACCESS_TOKEN,
refresh_token=REFRESH_TOKEN)
try:
now = datetime.datetime.now()
end_time = now.strftime("%H:%M")
response = client.intraday_time_series('activities/steps',
detail_level='15min',
start_time="00:00",
end_time=end_time)
except Exception as error:
print(error)
else:
str_steps = response['activities-steps'][0]['value']
print(str_steps)
try:
num_steps = int(str_steps)
except ValueError:
pass
return num_steps
示例4: form
# 需要导入模块: import fitbit [as 别名]
# 或者: from fitbit import Fitbit [as 别名]
def form():
"""Display today's entry form."""
#NOTE: Calling Fitbit API using Python Fitbit library, which only provides
#limited user data. For more data, must make a manual request to Fitbit API.
#NOTE: Accessing user data via implicit grant authorization flow. This auth
#flow only works for the currently logged in user. For increased security
#and app usage by others, must implement OAuth.
authd_client = fitbit.Fitbit(consumer_key, consumer_secret,
access_token=access_token, refresh_token=refresh_token)
sleep_log = authd_client.sleep()
hours_sleep = sleep_log['summary']['totalMinutesAsleep'] / 60
return render_template("entry.html",
hours_sleep = hours_sleep)
##########################################################################
示例5: test_response_ok
# 需要导入模块: import fitbit [as 别名]
# 或者: from fitbit import Fitbit [as 别名]
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()
示例6: test_response_auth
# 需要导入模块: import fitbit [as 别名]
# 或者: from fitbit import Fitbit [as 别名]
def test_response_auth(self):
"""
This test checks how the client handles different auth responses, and
the exceptions raised by the client.
"""
r = mock.Mock(spec=requests.Response)
r.status_code = 401
r.content = b"{'normal': 'resource'}"
f = Fitbit(**self.client_kwargs)
f.client._request = lambda *args, **kwargs: r
self.assertRaises(exceptions.HTTPUnauthorized, f.user_profile_get)
r.status_code = 403
self.assertRaises(exceptions.HTTPForbidden, f.user_profile_get)
示例7: test_response_error
# 需要导入模块: import fitbit [as 别名]
# 或者: from fitbit import Fitbit [as 别名]
def test_response_error(self):
"""
Tests other HTTP errors
"""
r = mock.Mock(spec=requests.Response)
r.content = b"{'normal': 'resource'}"
f = Fitbit(**self.client_kwargs)
f.client._request = lambda *args, **kwargs: r
r.status_code = 404
self.assertRaises(exceptions.HTTPNotFound, f.user_profile_get)
r.status_code = 409
self.assertRaises(exceptions.HTTPConflict, f.user_profile_get)
r.status_code = 500
self.assertRaises(exceptions.HTTPServerError, f.user_profile_get)
r.status_code = 499
self.assertRaises(exceptions.HTTPBadRequest, f.user_profile_get)
示例8: test_too_many_requests
# 需要导入模块: import fitbit [as 别名]
# 或者: from fitbit import Fitbit [as 别名]
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)
示例9: request_oauth_completion
# 需要导入模块: import fitbit [as 别名]
# 或者: from fitbit import Fitbit [as 别名]
def request_oauth_completion(hass):
"""Request user complete Fitbit OAuth2 flow."""
configurator = get_component('configurator')
if "fitbit" in _CONFIGURING:
configurator.notify_errors(
_CONFIGURING['fitbit'], "Failed to register, please try again.")
return
# pylint: disable=unused-argument
def fitbit_configuration_callback(callback_data):
"""The actions to do when our configuration callback is called."""
start_url = '{}{}'.format(hass.config.api.base_url, FITBIT_AUTH_START)
description = "Please authorize Fitbit by visiting {}".format(start_url)
_CONFIGURING['fitbit'] = configurator.request_config(
hass, 'Fitbit', fitbit_configuration_callback,
description=description,
submit_caption="I have authorized Fitbit."
)
示例10: update
# 需要导入模块: import fitbit [as 别名]
# 或者: from fitbit import Fitbit [as 别名]
def update(self):
"""Get the latest data from the Fitbit API and update the states."""
container = self.resource_type.replace("/", "-")
response = self.client.time_series(self.resource_type, period='7d')
self._state = response[container][-1].get('value')
if self.resource_type == 'activities/heart':
self._state = response[container][-1]. \
get('value').get('restingHeartRate')
config_contents = {
ATTR_ACCESS_TOKEN: self.client.client.token['access_token'],
ATTR_REFRESH_TOKEN: self.client.client.token['refresh_token'],
ATTR_CLIENT_ID: self.client.client.client_id,
ATTR_CLIENT_SECRET: self.client.client.client_secret,
ATTR_LAST_SAVED_AT: int(time.time())
}
if not config_from_file(self.config_path, config_contents):
_LOGGER.error("Failed to save config file")
示例11: __init__
# 需要导入模块: import fitbit [as 别名]
# 或者: from fitbit import Fitbit [as 别名]
def __init__(self, fitbitCredsFile, googleCredsFile):
""" Intialize a helper object.
fitbitCredsFile -- Fitbit credentials file
googleCredsFile -- Google Fits credentials file
"""
self.fitbitCredsFile = fitbitCredsFile
self.googleCredsFile = googleCredsFile
示例12: GetFitbitClient
# 需要导入模块: import fitbit [as 别名]
# 或者: from fitbit import Fitbit [as 别名]
def GetFitbitClient(self):
"""Returns an authenticated fitbit client object"""
logging.debug("Creating Fitbit client")
credentials = json.load(open(self.fitbitCredsFile))
client = fitbit.Fitbit(**credentials)
logging.debug("Fitbit client created")
return client
示例13: import_user_fitbit_history_via_api
# 需要导入模块: import fitbit [as 别名]
# 或者: from fitbit import Fitbit [as 别名]
def import_user_fitbit_history_via_api(user, start_date, end_date):
fitbit_user = UserFitbit.objects.get(user=user)
fitbit_api = fitbit.Fitbit(
client_id=settings.FITBIT_CONSUMER_KEY,
client_secret=settings.FITBIT_CONSUMER_SECRET,
access_token=fitbit_user.access_token,
expires_at=fitbit_user.expires_at,
refresh_token=fitbit_user.refresh_token,
refresh_cb=fitbit_user.refresh_cb,
)
query_dates = pd.date_range(start=start_date, end=end_date).date
for query_date in query_dates:
api_response = fitbit_api.get_sleep(query_date)
valid_data = api_response.get('sleep')
if not valid_data:
# if the response doesn't contain valid data, no sense to continue
continue
for datum in valid_data:
data = {
'user': user.id,
'start_time': datum['startTime'],
'end_time': datum['endTime']
}
serializer = FitbitResponseSleepActivitySerializer(data=data)
serializer.is_valid()
serializer.save()
示例14: fitbit_client
# 需要导入模块: import fitbit [as 别名]
# 或者: from fitbit import Fitbit [as 别名]
def fitbit_client(fitbit_credentials):
config = get_current_config()
client = fitbit.Fitbit(
config.FITBIT_CLIENT_ID,
config.FITBIT_CLIENT_SECRET,
access_token=fitbit_credentials.access_token,
refresh_token=fitbit_credentials.refresh_token
)
yield client
# Save in case we did some refreshes
save_fitbit_token(
fitbit_credentials.user_id,
client.client.token['access_token'],
client.client.token['refresh_token']
)
示例15: test_serialization
# 需要导入模块: import fitbit [as 别名]
# 或者: from fitbit import Fitbit [as 别名]
def test_serialization(self):
"""
Tests non-json data returned
"""
r = mock.Mock(spec=requests.Response)
r.status_code = 200
r.content = b"iyam not jason"
f = Fitbit(**self.client_kwargs)
f.client._request = lambda *args, **kwargs: r
self.assertRaises(exceptions.BadResponse, f.user_profile_get)