|
#!/usr/bin/python |
|
|
|
from os import path, access, R_OK |
|
import json |
|
import urllib2 |
|
import datetime |
|
|
|
gauge = { |
|
'id' : 'YOURID', # The ID can be found in your Gauge's Dashboard URL, e.g. https://secure.gaug.es/dashboard#/gauges/685d4566673fefh4ab7ff76d/overview -> ID = 685d4566673fefh4ab7ff76d |
|
'title' : 'My Website', # Title of your website, don't use any commas! |
|
'site' : 'my-website' # Abbreviation for the file name |
|
} |
|
|
|
api = { |
|
'url' : 'https://secure.gaug.es/gauges/', |
|
'header' : 'X-Gauges-Token', |
|
'token' : 'YOURTOKEN' # Get your API key here: https://secure.gaug.es/dashboard#/account/clients |
|
} |
|
|
|
report = { |
|
'path' : '/path/to/your/directory/', # Directory in which the CSV file will be created |
|
'file' : 'report-' + gauge['site'] + '.csv', |
|
} |
|
|
|
|
|
FILE = report['path'] + report['file'] |
|
HEADER = gauge['title'] + ",Views,People\n" |
|
|
|
|
|
def getJSON(url, header, token): |
|
req = urllib2.Request(url) |
|
req.add_header(header, token) |
|
opener = urllib2.build_opener() |
|
f = opener.open(req) |
|
return json.load(f) |
|
|
|
|
|
def appendViews(): |
|
|
|
# Get date |
|
today = datetime.date.today() |
|
yesterday = today - datetime.timedelta(1) |
|
checkDate = yesterday.strftime("%Y-%m-%d") |
|
|
|
# Get traffic |
|
trafficURL = api['url'] + gauge['id'] + '/traffic?date=' + checkDate |
|
j = getJSON(trafficURL, api['header'], api['token']) |
|
|
|
date = j['date'] |
|
latest = len(j['traffic'])-2 |
|
today = j['traffic'][latest] |
|
views = today['views'] |
|
people = today['people'] |
|
|
|
# Write to file |
|
f.write(date + ',' + str(views) + ',' + str(people) + '\n') |
|
|
|
|
|
# File exists and is readable |
|
if path.isfile(FILE) and access(FILE, R_OK): |
|
|
|
# Read first line |
|
f = open(FILE, 'r') |
|
firstLine = f.readline() |
|
f.closed |
|
|
|
# HEADER matches -> append views |
|
if firstLine == HEADER: |
|
f = open(FILE, 'a') |
|
appendViews() |
|
f.closed |
|
|
|
# HEADER doesn't match -> overwrite file |
|
else: |
|
f = open(FILE, 'w') # change 'w' to 'a' if you don't want to override the file, but to append the correct HEADER and views |
|
f.write(HEADER) |
|
appendViews() |
|
f.closed |
|
|
|
# File doesn't exist |
|
else: |
|
|
|
f = open(FILE, 'w') |
|
f.write(HEADER) |
|
appendViews() |
|
f.closed |