-
Notifications
You must be signed in to change notification settings - Fork 3
/
instant-api.py
executable file
·62 lines (43 loc) · 1.61 KB
/
instant-api.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
#!/usr/bin/python
import string
import json
import sys
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from argparse import ArgumentParser
parser = ArgumentParser(description='Process some integers.')
parser.add_argument("-f", "--file", dest="filename",
help="JSON file to serve", metavar="FILE")
parser.add_argument("-p", "--port", dest="port",
help="Port to listen on", metavar="PORT")
args = parser.parse_args().__dict__
file_arg = args['filename'] or "source.json"
port_arg = args['port'] or "8080"
port = 8080 if port_arg is None else int(port_arg)
class InstantAPIServer(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
path = self.path[1:]
components = string.split(path, '/')
try:
node = json.loads(open(file_arg).read())
except IOError:
print "Couldn't find file '%s'" % file_arg
sys.exit()
for component in components:
if len(component) == 0 or component == "favicon.ico":
continue
if type(node) == dict:
node = node[component]
elif type(node) == list:
node = node[int(component)]
self.wfile.write(json.dumps(node))
return
try:
server = HTTPServer(('', port), InstantAPIServer)
print 'Starting instant API server on port %s...' % (port)
server.serve_forever()
except KeyboardInterrupt:
print 'Stopping instant API server...'
server.socket.close()