forked from jamesmeneghello/pynab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
66 lines (50 loc) · 1.89 KB
/
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
63
64
65
66
import re
import bottle
from bottle import request, response
import xmltodict
from pynab import log
import pynab.api
app = application = bottle.Bottle()
@app.get('/api')
def api():
log.debug('Handling request for {0}.'.format(request.fullpath))
# these are really basic, don't check much
function = request.query.t or pynab.api.api_error(200)
for r, func in pynab.api.functions.items():
# reform s|search into ^s$|^search$
# if we don't, 's' matches 'caps' (s)
r = '|'.join(['^{0}$'.format(r) for r in r.split('|')])
if re.search(r, function):
dataset = dict()
dataset['get_link'] = get_link
data = func(dataset)
output_format = request.query.o or 'xml'
if output_format == 'xml':
# return as xml
response.set_header('Content-type', 'application/rss+xml')
return data
elif output_format == 'json':
# bottle auto-converts into json
return xmltodict.parse(data)
else:
return pynab.api.api_error(201)
# didn't match any functions
return pynab.api.api_error(202)
def get_link(route=''):
"""Gets a link (including domain/subdirs) to a route."""
url = request.environ['wsgi.url_scheme'] + '://'
if request.environ.get('HTTP_HOST'):
url += request.environ['HTTP_HOST']
else:
url += request.environ['SERVER_NAME']
if request.environ['wsgi.url_scheme'] == 'https':
if request.environ['SERVER_PORT'] != '443':
url += ':' + request.environ['SERVER_PORT']
else:
if request.environ['SERVER_PORT'] != '80':
url += ':' + request.environ['SERVER_PORT']
if route:
url += app.get_url(route)
return url
if __name__ == '__main__':
bottle.run(app=app, host='0.0.0.0', port=8080)