forked from eventdata/spec-event-data-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
110 lines (89 loc) · 2.86 KB
/
app.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
from flask import Flask
from flask import request, Response
from pymongo.mongo_client import MongoClient
from bson.json_util import dumps
from io import StringIO
import json
import sys
import urllib
from dateutil import parser
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS']=True
mongo_ip = "10.176.148.60"
mongoClient = MongoClient(host=mongo_ip)
api_key = 'CD75737EF4CAC292EE17B85AAE4B6'
project_dict = {
"code": 1,
"target": 1,
"headline": 1,
"country": 1,
"coordinates": 1,
"content": 1,
"source": 1,
"link": 1,
"location": 1,
"date": 1,
"_id": 1
}
def create_project_dict(proj_str, delim=','):
fields = proj_str.split(delim)
proj_dict = {}
for f in fields:
proj_dict[f.strip()] = 1
return proj_dict
def query_formatter(query_dict):
for key in query_dict:
if isinstance(query_dict[key], dict):
query_formatter(query_dict[key])
else:
if str(query_dict[key]).startswith("$date"):
date_str = str(query_dict[key]).replace("$date", "").replace("(", "").replace(")","").strip()
date_obj = parser.parse(date_str)
query_dict[key] = date_obj
def get_result(query, projection=None):
print "Inside Method"
try:
print query
mongoClient = MongoClient()
db = mongoClient.spec
print query
query_dict = json.load(StringIO(unicode(query, 'utf-8')))
print "Got Data"
cursor = None
query_formatter(query_dict)
print query_dict
if projection is not None:
proj_dict = create_project_dict(projection)
cursor = db.cameo_events.find(query_dict, proj_dict)
else:
cursor = db.cameo_events.find(query_dict)
print "Got Data"
return '{"status": "success", "data": '+dumps(cursor)+"}"
except:
e = sys.exc_info()[0]
print e
return '{"status": "error", "data":'+str(e)+"}"
@app.route("/api/data")
def get_data():
query = request.args.get('query')
projection = request.args.get('select')
print projection
print query
response_data = ""
api_key_received = request.args.get('api_key')
try:
if api_key_received == api_key:
response_data = get_result(str(urllib.unquote_plus(query)), projection)
else:
response_data = '{"status": "error", "data":"invalid api key"}"'
resp = Response(response_data, mimetype='application/json')
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
except:
e = sys.exc_info()[0]
print e
resp = Response('{"status": "error", "data":"'+str(e)+'"}')
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
if __name__ == "__main__":
app.run(host='0.0.0.0')