-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathesflask.py
178 lines (143 loc) · 4.34 KB
/
esflask.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
from flask import render_template,request,Flask,json
from outis import elastopy
from werkzeug import secure_filename
from werkzeug.wsgi import LimitedStream
from datetime import datetime, timedelta
import csv
import os
from flask.ext.cors import CORS
c=elastopy()
temp_index = 'outis/test_index'
class StreamConsumingMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
stream = LimitedStream(environ['wsgi.input'],
int(environ['CONTENT_LENGTH'] or 0))
environ['wsgi.input'] = stream
app_iter = self.app(environ, start_response)
try:
stream.exhaust()
for event in app_iter:
yield event
finally:
if hasattr(app_iter, 'close'):
app_iter.close()
app = Flask(__name__, static_folder='static')
UPLOAD_FOLDER = os.path.dirname(os.path.realpath(__file__))+'/uploads'
print UPLOAD_FOLDER
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
CORS(app)
@app.route('/')
def dashboard():
return render_template('/home.html',indexes=c.get_indices())
@app.route('/api/v1/data/search',methods=['GET','POST'])
def search():
from tzlocal import get_localzone
import iso8601
from datetime import datetime
from pytz import timezone
if request.method == 'POST':
data=request.get_json()
search_data=[]
try:
if data['option'] == '10d' :
interval='d'
rounding='d'
time_param='%b %d '
elif data['option'] == '7d':
data['option']='1h'
interval='d'
time_param='%b %d '
rounding='w'
elif data['option'] == '1M':
data['option']='1d'
interval='d'
time_param='%b %d '
rounding='M'
elif data['option'] == '1y':
data['option']='1d'
interval='M'
time_param=' %b %Y'
rounding='y'
elif data['option'] == '2y':
data['option']='1y'
interval='M'
time_param=' %b %Y'
rounding='y'
else:
interval = 'y'
time_param='%Y '
rounding='y'
val=c.search(data['query'],['something'],data['option'],interval,rounding,temp_index)
for i in val['hits']['hits']:
time=i['_source']['time']
local_tz = get_localzone()
m=iso8601.parse_date(time)
time_utc=m.astimezone(timezone('UTC'))
local_time=time_utc.astimezone(local_tz)
i['_source']['time']=local_time.strftime('%A, %B %d, %Y at %H:%M hours')
search_data.append(i)
if search_data==[]:
search_data=["No entries found"]
except:
search_data=["No entries found "]
l=c.map_key(temp_index)
l=l.keys()
global outis1,outis2
outis1= search_data
for idx,value in enumerate(val['aggregations']['2']['buckets']):
time=val['aggregations']['2']['buckets'][idx]['key_as_string']
p=datetime.strptime(time,'%Y-%m-%dT%H:%M:%S.%f+{}'.format(time[-5:]))
val['aggregations']['2']['buckets'][idx]['key_as_string']=p.strftime("{}".format(time_param))
search_data.append(val['aggregations']['2']['buckets'])
return json.dumps(search_data)
@app.route('/api/v1/data/estimate',methods=['POST'])
def aggregate():
if request.method == 'POST':
data=request.get_json()
l=c.aggregate(data['option'],data['query'],temp_index)
if data['option'] == 'terms':
return json.dumps(l['sample_name']['buckets'])
else:
return json.dumps(l['sample_name']['value'])
@app.route('/api/v1/data/upload',methods=['POST'])
def upload():
if request.method =='POST':
file = request.files['file']
if file:
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
c.upload(filename,temp_index,UPLOAD_FOLDER)
return 'success'
@app.route('/api/v1/data/export',methods=['POST'])
def export():
if request.method == 'POST':
data=json.loads(request.body)
l=c.map_key(temp_index)
l=l.keys()
l.sort()
l2=[]
for items in l:
try:
if data[items] == True:
l2.append(items)
except:
pass
global outis1
with open('outis/static/data.csv', 'wb') as output_file:
dict_writer = csv.DictWriter(output_file, l2,extrasaction='ignore')
dict_writer.writeheader()
try:
for k in outis1[:-1]:
dict_writer.writerows([k['_source']])
except:
pass
file_data=open("static/data.csv", "rb").read()
resp=HttpResponse(file_data,content_type='text/csv;charset=utf-8')
resp['Content-Disposition'] = 'attachment;filename=table.csv'
return resp
if __name__ == "__main__":
app.debug = True
app.run()
app.wsgi_app = StreamConsumingMiddleware(app.wsgi_app)