|
1 ''' |
|
2 Proxy server for getting hyperthesis annotation |
|
3 ''' |
|
4 import os |
|
5 |
|
6 import bottle |
|
7 import requests |
|
8 from bottle import route, response |
|
9 |
|
10 app = application = bottle.Bottle() |
|
11 |
|
12 config_file_path = os.getenv('CONFIG_PATH', "hypothesis_proxy.conf") |
|
13 |
|
14 app.config.load_config(config_file_path) |
|
15 |
|
16 # From https://stackoverflow.com/a/17262900 |
|
17 class EnableCors(object): |
|
18 name = 'enable_cors' |
|
19 api = 2 |
|
20 |
|
21 def apply(self, fn, context): |
|
22 def _enable_cors(*args, **kwargs): |
|
23 # set CORS headers |
|
24 response.headers['Access-Control-Allow-Origin'] = '*' |
|
25 response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS' |
|
26 response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token' |
|
27 |
|
28 if bottle.request.method != 'OPTIONS': |
|
29 # actual request; reply with the actual response |
|
30 return fn(*args, **kwargs) |
|
31 |
|
32 return _enable_cors |
|
33 |
|
34 app.install(EnableCors()) |
|
35 |
|
36 @app.route('/annotations') |
|
37 def query_hypothesis(): |
|
38 ''' |
|
39 query hypothesis |
|
40 ''' |
|
41 |
|
42 annotations_json = app.config.get('proxy.annotations_json', None) |
|
43 |
|
44 if annotations_json and os.path.isfile(annotations_json): |
|
45 import json |
|
46 with open(annotations_json, 'r') as f: |
|
47 return json.load(f) |
|
48 |
|
49 url = app.config.get('proxy.url', 'https://h.projet-episteme.org/api/search') |
|
50 headers = {} |
|
51 token = app.config.get('proxy.token') |
|
52 if token is not None: |
|
53 headers["Authorization"] = "Bearer " + token |
|
54 |
|
55 params = {} |
|
56 for config_tag in ['group', 'user', 'tag', 'limit']: |
|
57 config_val = app.config.get('proxy.%s' % config_tag) |
|
58 if config_val is not None: |
|
59 params[config_tag] = config_val |
|
60 |
|
61 offset = 0 |
|
62 total = -1 |
|
63 |
|
64 rows = [] |
|
65 |
|
66 while total < 0 or offset < total: |
|
67 #TODO: handle errors |
|
68 res = requests.get(url, params=params, headers=headers) |
|
69 res_json = res.json() |
|
70 total = int(res_json['total']) |
|
71 rows += res_json['rows'] |
|
72 offset = len(rows) |
|
73 params['offset'] = offset |
|
74 |
|
75 return { |
|
76 'rows': rows, |
|
77 'total': len(rows) |
|
78 } |
|
79 |
|
80 |
|
81 if __name__ == "__main__": |
|
82 app.run( |
|
83 host=app.config.get('proxy.host', '127.0.0.1'), |
|
84 port=int(app.config.get('proxy.port', 8888)) |
|
85 ) |