Last active
March 5, 2019 22:48
-
-
Save bradmontgomery/a09fccf4e2ec97439c46a0aa6b0547bb to your computer and use it in GitHub Desktop.
Example code to fetch accelerometer data from the Preteckt API.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
This example python code shows how to appropriately query the Preteckt | |
accelerometer API for data over a date range. | |
Run with: | |
$ python get_accel_data.py | |
NOTE: Running this code in python3 is recommended. | |
""" | |
import requests # Requires the requets package: pip install requests | |
from datetime import datetime, timedelta | |
from time import sleep | |
# See: https://dash.preteckt.us/accounts/ | |
API_KEY = 'ADD-YOUR-API-KEY-HERE' | |
# The preteckt unit number whose data you want. Your account must have | |
# permission to view data for this unit. | |
UNIT = 247 | |
# The total time period for data of interest. | |
START = '2018-09-01T00:00:00' | |
END = '2018-10-31T23:59:59' | |
# Request 3 days worth of data at a time. | |
CHUNK = 3 | |
# The accelerometer API endpoint. | |
URL = 'https://dash.preteckt.us/api/rtdv/accelerometer/' | |
def get(unit, start, end, chunk): | |
# Convert our start/end times to datetime objects. | |
date_format = '%Y-%m-%dT%H:%M:%S' # string format for all datetimes | |
start = datetime.strptime(start, date_format) | |
end = datetime.strptime(end, date_format) | |
# In order to log in, we need to set an authorization header for | |
# every HTTP request. | |
headers = {'Authorization': "Token {}".format(API_KEY)} | |
# Fetch our data chunk days at a time. | |
while start <= end: | |
td = timedelta(days=chunk) # a time window of size "chunk" days. | |
payload = { | |
'unit_number': unit, | |
'from_time': start.strftime(date_format), | |
'to_time': (start + td).strftime(date_format), | |
} | |
resp = requests.get(URL, params=payload, headers=headers) | |
data = resp.json() | |
if resp.status_code == 200: | |
# This example prints the response payload, but you could | |
# alter this to write the data to a file. | |
print(data) | |
# Add a chunk of time to the starting | |
start = start + td | |
else: | |
print("Unable to fetch data. Status: {}".format(resp.status_code)) | |
print(data) | |
start = start + timedelta(days=365 * 9000) | |
sleep(1) # sleep 1 second just to be kind to the api. | |
if __name__ == "__main__": | |
get(UNIT, START, END, CHUNK) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment