|
| 1 | +import logging |
| 2 | +from collections import defaultdict |
| 3 | +import tornado.web |
| 4 | +import tornado.httpclient |
| 5 | + |
| 6 | +class ElasticProxyHandler(tornado.web.RequestHandler): |
| 7 | + |
| 8 | + RoutePath = r'/api/v1/elastic/proxy/(.*)' |
| 9 | + |
| 10 | + @tornado.web.asynchronous |
| 11 | + def forward(self, path): |
| 12 | + body = None if self.request.body == '' else self.request.body |
| 13 | + path = self.request.uri.split('proxy/')[1] |
| 14 | + client = tornado.httpclient.AsyncHTTPClient() |
| 15 | + client.fetch('http://localhost:9200/' + path, |
| 16 | + method=self.request.method, |
| 17 | + body=body, |
| 18 | + headers=self.request.headers, |
| 19 | + follow_redirects=False, |
| 20 | + callback=self.callback) |
| 21 | + |
| 22 | + # aliases |
| 23 | + get = forward |
| 24 | + put = forward |
| 25 | + post = forward |
| 26 | + delete = forward |
| 27 | + |
| 28 | + def callback(self, request): |
| 29 | + self.finish(request.body) |
| 30 | + |
| 31 | + |
| 32 | +class ElasticSearchHandler(tornado.web.RequestHandler): |
| 33 | + |
| 34 | + RoutePath = r'/api/v1/elastic/search' |
| 35 | + |
| 36 | + @tornado.web.asynchronous |
| 37 | + def post(self): |
| 38 | + search = QueryParser.parse(self.request.body) |
| 39 | + client = tornado.httpclient.AsyncHTTPClient() |
| 40 | + client.fetch('http://localhost:9200/' + path, |
| 41 | + method='POST', body=search, callback=self.callback) |
| 42 | + |
| 43 | + def callback(self, request): |
| 44 | + self.finish(request.body) |
| 45 | + |
| 46 | +# ------------------------------------------------------------ |
| 47 | +# query parser |
| 48 | +# ------------------------------------------------------------ |
| 49 | +class QueryParser(object): |
| 50 | + |
| 51 | + @staticmethod |
| 52 | + def parse(request): |
| 53 | + query = {} |
| 54 | + for piece in request.split(' '): |
| 55 | + if 'size' in piece: |
| 56 | + field, value = piece.split('=') |
| 57 | + query['size'] = value |
| 58 | + if 'from' in piece: |
| 59 | + field, value = piece.split('=') |
| 60 | + query['from'] = value |
| 61 | + elif 'filter_' in piece: |
| 62 | + field, value = piece.split('=') |
| 63 | + field = field.split('filter_')[1] |
| 64 | + query['filter']['term'][field] = value |
| 65 | + elif '=' in piece: |
| 66 | + field, value = piece.split('=') |
| 67 | + query['query']['term'][field] = value |
| 68 | + else: |
| 69 | + query['text']['_all'] = |
| 70 | + |
| 71 | + |
| 72 | +# ------------------------------------------------------------ |
| 73 | +# exports |
| 74 | +# ------------------------------------------------------------ |
| 75 | +__all__ = ['ElasticProxyHandler'] |
0 commit comments