~mhall119/+junk/click-store-stats

« back to all changes in this revision

Viewing changes to ubuntustats/stats.py

  • Committer: mhall119
  • Date: 2013-10-29 19:15:53 UTC
  • Revision ID: mhall119@ubuntu.com-20131029191553-fk065fquxynwlfh4
initial graph scripts

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
from paths import data_dir
 
2
 
 
3
import time
 
4
import json
 
5
import os
 
6
 
 
7
UPDATE_INTERVAL = 60 * 60
 
8
 
 
9
def needs_update(filename):
 
10
    data_file = os.path.join(data_dir, filename)
 
11
    return (not os.path.exists(data_file)) or \
 
12
           (time.time()-os.path.getctime(data_file) >= UPDATE_INTERVAL)
 
13
 
 
14
def read_lines(filename, path=None):
 
15
        dirname = data_dir
 
16
        if path:
 
17
                dirname = path
 
18
        data_file = os.path.join(dirname, filename)
 
19
        lines = open(data_file, "r").readlines()
 
20
        return map(lambda a: a.strip(), lines)
 
21
 
 
22
def read_data(filename=None, fd=None):
 
23
    if not fd:
 
24
        if not filename:
 
25
            return []
 
26
        data_file = os.path.join(data_dir, filename)
 
27
        if not os.path.exists(data_file):
 
28
            return []
 
29
        fd = open(data_file)
 
30
    return json.loads(fd.read())
 
31
 
 
32
def sanitise_data(data):
 
33
    for entry in data:
 
34
        if type(entry) in [ list, tuple ]:
 
35
            # sometimes we get "None" back from LP
 
36
            for what in entry[1]:
 
37
                if what in [ None, "None"]:
 
38
                    entry_index = data.index(entry)
 
39
                    what_index  = data[entry_index][1].index(what)
 
40
                    data[entry_index][1][what_index] = data[entry_index-1][1][what_index]
 
41
    return data
 
42
 
 
43
def dump(filename, data):
 
44
    data_file = os.path.join(data_dir, filename)
 
45
    if os.path.exists(data_file):
 
46
        os.remove(data_file)
 
47
    else:
 
48
        if not os.path.exists(data_dir):
 
49
            os.makedirs(data_dir)
 
50
    f = open(data_file, 'a')
 
51
    f.write(json.dumps(data))
 
52
    f.close()
 
53
 
 
54
def add_stats(filename, what, timestamp=None, unique=False):
 
55
    if not what:
 
56
        return False
 
57
    if not timestamp:
 
58
        timestamp = int(time.time())
 
59
    data = read_data(filename)
 
60
    
 
61
    if type(what) not in [ tuple, list ]:
 
62
        what = [what]
 
63
    
 
64
    if unique and data and data[-1][1] == what:
 
65
        data[-1][0] = timestamp
 
66
    else:
 
67
        data += [[timestamp, what]]
 
68
    data = sanitise_data(data)
 
69
    dump(filename, data)
 
70
    return True