-
Notifications
You must be signed in to change notification settings - Fork 1
/
getFactual.py
227 lines (185 loc) · 5.48 KB
/
getFactual.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#
# written by Mike Borozdin
# @mikebz
#
# please keep the author's name in the code file if you are using
# this IP
#
import json
from httplib import HTTPConnection
from pprint import pprint
import sys
import string
from array import array
from django.utils.encoding import smart_str, smart_unicode
api_key = "get this from factual.com"
'''
get the table data
'''
def get_table_data(table, search = ""):
url = "http://api.factual.com"
conn = HTTPConnection("api.factual.com")
query = "/v2/tables/" + table + "/read?"
if( search != "" ):
query += "filters={\"$search\":\"" + search + "\"}&"
conn.request("GET", query + "api_key=" + api_key)
resp = conn.getresponse()
status = resp.status
if status == 200 or status == 304:
return resp.read()
print result
else:
print 'Error status code: ', status
return "";
def get_table_schema(table):
url = "http://api.factual.com"
conn = HTTPConnection("api.factual.com")
conn.request("GET", "/v2/tables/" + table + "/schema?api_key=" + api_key)
resp = conn.getresponse()
status = resp.status
if status == 200 or status == 304:
return resp.read()
print result
else:
print 'Error status code: ', status
return "";
def print_table(data, row_ids = [] ):
#DEBUG
#print 'in print_table'
#pprint(row_ids)
for row in data['response']['data']:
for i in range( min(len(row), len(row_ids))):
sys.stdout.write('-------------------------------')
print ""
for i in range(1, len(row) ): #there is a weird additional row
cell = row[i]
# handle the case when only certain row ids
# were selected
# NOTE: adjusting for some additional row here.
if( len(row_ids) == 0 or (i-1) in row_ids):
value = smart_str(cell)
if( len(value) > 30):
value = value[:26] + '...'
sys.stdout.write( "|{0:29}".format(value))
# else:
# DEBUG
# sys.stdout.write( "|{0:30}".format('skipped cell'))
print "|"
def print_table_list(data):
for row in data['response']['data']:
print row[2]
def handle_describe(x):
tokens = x.split()
if len( tokens ) < 2:
print 'you need to provide a table name'
return
result = get_table_data("hPMZ80", tokens[1])
data = json.loads(result)
if ( len(data['response']['data']) < 1 ):
print 'No table that matches your query'
else:
print 'Loading table data for: ' + tokens[1]
table_id = data['response']['data'][0][7]
result = get_table_schema(table_id)
schema_data = json.loads(result)
for field in schema_data['schema']['fields']:
print '.' + field['name'] + ' : ' + field['datatype']
#pprint(schema_data)
def table_id_lookup(table_name):
result = get_table_data("hPMZ80", table_name)
data = json.loads(result)
if ( len(data['response']['data']) < 1 ):
print 'No table that matches your query'
return ""
else:
table_id = data['response']['data'][0][7]
return table_id;
'''
this function will take a table and fields and return the columns for those ids
'''
def table_row_lookup(table_id, fields):
#DEBUG
#print 'in table_row_lookup'
#pprint(fields)
columns = []; #create an empty collection to append
result = get_table_schema(table_id) #this returns a schema part of which is fields
schema_data = json.loads(result)
i = 0
#
# for every field see if it's also in the "fields" paramter
# if it is then append it's index, if not then just move on.
for field in schema_data['schema']['fields']:
#DEBUG
#print 'field:'
#pprint(field)
if field['name'] in fields:
columns.append(i)
i += 1
#DEBUG
#print 'return'
#pprint (columns)
return columns
def handle_select(x):
tokens = []
# a little weird tokenizing to get rid of the separators
for tok1 in x.split():
for tok2 in tok1.split(','):
tokens.append(tok2)
#first ensure it looks like a real select
if( tokens[0] != 'select'):
print 'improper syntax: select statement is not starting with \"select...\"'
return
if not 'from' in tokens:
print 'select statement needs to end with "from <table_name>"'
return
if tokens.index('from') == len(tokens) - 1:
print 'select statement needs to end with "from <table_name>"'
return
if tokens.index('from') == 1:
print 'please provide some fields to select or use "*"'
return
# lot's of assumptions here, but this is a hackathon after all
table_name = tokens[len(tokens) - 1]
fields = tokens[1 : -2]
table_id = table_id_lookup( table_name )
result = get_table_data( table_id )
data = json.loads(result)
# if there is a star we will just dump it all out.
if( '*' in fields ):
print_table(data)
return
else:
row_ids = table_row_lookup(table_id, fields)
print_table(data, row_ids)
def print_help():
print "Help is on the way!"
print "Current commands: test, help, quit, tables, describe, select"
'''
The main function that parses user input
'''
if __name__ == "__main__":
x = ""
while x != 'quit' and x != 'exit' and x != 'q':
x = raw_input('factual command> ')
x = x.lower().strip()
if x == "test":
result = get_table_data("GxpamT")
data = json.loads(result)
print_table(data)
elif x == 'tables':
result = get_table_data("hPMZ80")
data = json.loads(result)
print_table_list(data)
elif x.startswith('describe'):
handle_describe(x)
elif x.startswith('select'):
handle_select(x)
# all the quitting functions
elif x == "quit":
print "exiting..."
elif x == "q":
print "exiting..."
elif x == "exit":
print "exiting..."
else:
print 'does not compute. type help or quit'