-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
132 lines (100 loc) · 3.22 KB
/
main.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
import requests as r
from flask import Flask, request, jsonify, render_template
app = Flask(__name__)
ACCES_URL = 'https://api.askdata.com/security/domain/askdata/oauth/token'
WORKSPACE_URL = 'https://api.askdata.com/smartfeed/askdata/workspace/switch'
QUERY_URL = 'https://api.askdata.com/smartinsight/data/nl/result'
def get_token(username, password):
res = r.post(ACCES_URL,
data={
"grant_type": "password",
"username": username,
"password": password
},
headers={
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic ZmVlZDpmZWVk"
}
)
print(res.text)
return res.json()
def switch_workspace(token):
res = r.post(WORKSPACE_URL,
json={
"agent_slug": "pi_day"
},
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {token}"
}
)
return res.text
def make_query(query, lang, token):
res = r.post(QUERY_URL,
json={
"nl": query,
"language": lang
},
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {token}"
}
)
return res.json()
def prettify_data(result):
data = result["data"]
results = []
for el in data:
results.append(el["cells"])
return {"data": results,
"sql_query": result["executedSQLQuery"]}
token = get_token(username="[email protected]",
password="Askdatahackathon")
switch_workspace(token=token["access_token"])
@app.route('/query', methods=['POST'])
def query():
print("Query Request")
input_data = request.get_json()
print(input_data)
query = input_data["query"].strip()
lang = input_data["lang"].strip()
global token
results = make_query(query=query,
lang=lang,
token=token["access_token"])
results = prettify_data(result=results)
if len(results) > 0:
print(results)
output = {
"query": query,
"lang": lang,
"data": results["data"],
"sql_query": results["sql_query"]
}
return jsonify(output)
@app.route('/query_get', methods=['GET'])
def query_get():
print("Query Request")
input_data = request.args
print(input_data)
query = input_data["query"].strip()
lang = input_data["lang"].strip()
global token
results = make_query(query=query,
lang=lang,
token=token["access_token"])
results = prettify_data(result=results)
if len(results) > 0:
print(results)
output = {
"query": query,
"lang": lang,
"data": results["data"],
"sql_query": results["sql_query"]
}
return jsonify(output)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5000)