forked from chiangf/Flask-Elasticsearch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflask_elasticsearch.py
49 lines (39 loc) · 1.85 KB
/
flask_elasticsearch.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
from elasticsearch import Elasticsearch
# Find the stack on which we want to store the database connection.
# Starting with Flask 0.9, the _app_ctx_stack is the correct one,
# before that we need to use the _request_ctx_stack.
try:
from flask import _app_ctx_stack as stack
except ImportError:
from flask import _request_ctx_stack as stack
class FlaskElasticsearch(object):
def __init__(self, app=None, **kwargs):
self.app = app
if app is not None:
self.init_app(app, **kwargs)
def init_app(self, app, **kwargs):
app.config.setdefault('ELASTICSEARCH_HOST', 'localhost:9200')
app.config.setdefault('ELASTICSEARCH_HTTP_AUTH', None)
self.elasticsearch_options = kwargs
# Use the newstyle teardown_appcontext if it's available,
# otherwise fall back to the request context
if hasattr(app, 'teardown_appcontext'):
app.teardown_appcontext(self.teardown)
else:
app.teardown_request(self.teardown)
def __getattr__(self, item):
ctx = stack.top
if ctx is not None:
if not hasattr(ctx, 'elasticsearch'):
if isinstance(ctx.app.config.get('ELASTICSEARCH_HOST'), str):
hosts = [ctx.app.config.get('ELASTICSEARCH_HOST')]
elif isinstance(ctx.app.config.get('ELASTICSEARCH_HOST'), list):
hosts = ctx.app.config.get('ELASTICSEARCH_HOST')
ctx.elasticsearch = Elasticsearch(hosts=hosts,
http_auth=ctx.app.config.get('ELASTICSEARCH_HTTP_AUTH'),
**self.elasticsearch_options)
return getattr(ctx.elasticsearch, item)
def teardown(self, exception):
ctx = stack.top
if hasattr(ctx, 'elasticsearch'):
ctx.elasticsearch = None