本文整理汇总了Python中fitbit.Fitbit.get_token_with_pin方法的典型用法代码示例。如果您正苦于以下问题:Python Fitbit.get_token_with_pin方法的具体用法?Python Fitbit.get_token_with_pin怎么用?Python Fitbit.get_token_with_pin使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类fitbit.Fitbit
的用法示例。
在下文中一共展示了Fitbit.get_token_with_pin方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: IndxClient
# 需要导入模块: from fitbit import Fitbit [as 别名]
# 或者: from fitbit.Fitbit import get_token_with_pin [as 别名]
# 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):
aggr = response["activities-steps"]
if len(aggr) > 1:
# add this later
print "several days worth of data, only processing the first day"
示例2: __init__
# 需要导入模块: from fitbit import Fitbit [as 别名]
# 或者: from fitbit.Fitbit import get_token_with_pin [as 别名]
class FitbitHarvester:
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
def set_config(self, args):
stored_config_harvester = keyring.get_password("INDX", "INDX_Fitbit_Harvester")
if stored_config_harvester is not None:
stored_config_harvester = json.loads(stored_config_harvester)
stored_config_fitbit = keyring.get_password("Fitbit.com", "Fitbit")
if stored_config_fitbit is not None:
stored_config_fitbit = json.loads(stored_config_fitbit)
received_config = json.loads(args['config'])
if (type(received_config) != dict):
received_config = json.loads(received_config)
self.logger.debug("Received config ({0}): {1}".format(type(received_config), received_config))
config = {}
if 'fitbit' in received_config:
fitbit_config = received_config['fitbit']
if fitbit_config and ('pin' in fitbit_config) and ('req_token' in fitbit_config): # this should check for the req_token in the stored config!
self.logger.debug("Received pin: {0}".format(fitbit_config['pin']))
try:
token = self.fitbit.get_token_with_pin(fitbit_config['pin'], fitbit_config['req_token'])
self.logger.debug("Got auth token {0}, of type {1}".format(token, type(token)))
if token:
config['token']=token
keyring.set_password("Fitbit.com", "Fitbit", json.dumps(config))
except Exception as exc:
self.logger.error("Could not authorise to fitbit, with pin {0}, error: {1}".format(fitbit_config['pin'], exc))
if 'harvester' in received_config:
harvester_config = received_config['harvester']
if harvester_config != stored_config_harvester:
keyring.set_password("INDX", "INDX_Fitbit_Harvester", json.dumps(harvester_config))
def get_config(self, args):
stored_config_harvester = keyring.get_password("INDX", "INDX_Fitbit_Harvester")
stored_config_fitbit = keyring.get_password("Fitbit.com", "Fitbit")
self.logger.debug("Loaded harvester config from keyring: {0}".format(stored_config_harvester))
self.logger.debug("Loaded fitbit config from keyring: {0}".format(stored_config_fitbit))
if stored_config_fitbit is None :
token_url = self.fitbit.get_token_url()
config_fitbit = {}
config_fitbit["url"] = token_url['url']
config_fitbit["req_token"] = token_url['req_token']
else :
if (type(stored_config_fitbit) != dict):
config_fitbit = json.loads(stored_config_fitbit)
# if (type(config_fitbit) != dict):
# config_fitbit = json.loads(config_fitbit)
if 'token' not in config_fitbit :
token_url = self.fitbit.get_token_url()
config_fitbit["url"] = token_url['url']
config_fitbit["req_token"] = token_url['req_token']
#.........这里部分代码省略.........
示例3: FitbitApp
# 需要导入模块: from fitbit import Fitbit [as 别名]
# 或者: from fitbit.Fitbit import get_token_with_pin [as 别名]
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)
#.........这里部分代码省略.........