This repository has been archived by the owner on Jun 9, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tracker.py
executable file
·69 lines (53 loc) · 2 KB
/
tracker.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# Import necessary Google API and time packages
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from datetime import datetime, timedelta
import json
import requests
# Import ipstack API Key
import config
# Traker class to manage variables and functions
class Tracker:
# Initialize the tracker
def __init__(self):
# Enable main.py to access Google spreadsheets
self.scope = scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
self.creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json',self.scope)
self.client = gspread.authorize(self.creds)
# Open sheet
self.sheet = self.client.open('location-data').sheet1
self.index = 2
# Import ipstack key
self.key = config.ipstack_key
self.send_url = 'http://api.ipstack.com/check?access_key={}'.format(self.key)
# If the first row is empty, add the header
if self.sheet.acell('A1').value=='':
self.make_header()
# Update settings
self.delta = timedelta(minutes=15)
# Make header
def make_header(self):
r = requests.get(self.send_url)
j = json.loads(r.text)
row = [list(j.keys())[index] for index in [0,3,5,6,8,9,10,11]]
row.insert(0, 'time')
self.sheet.insert_row(row, 1)
# Get location information and update sheet
def update_sheet(self):
# Request location information from ipstack API
r = requests.get(self.send_url)
j = json.loads(r.text)
# Isolate desired data
important_data = [0,3,5,6,8,9,10,11]
row = [j[list(j.keys())[index]] for index in important_data]
# Insert time
row.insert(0, str(datetime.now()))
# Update
self.sheet.insert_row(row, self.index)
# Main function
def main(self):
self.update_sheet()
if __name__ == "__main__":
tracker = Tracker()
tracker.main()