-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathviews.py
256 lines (213 loc) · 8.36 KB
/
views.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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
from app import app
#from cassandra.cluster import Cluster
import flask
from flask import jsonify, render_template, make_response, request
import json
from json import dumps
import geojson
from geojson import Feature, MultiLineString, FeatureCollection
import time
import sys
import datetime
# import MySQLdb as mdb
import pymysql as pdb
#cluster = Cluster(['54.175.15.242'])
##cluster = Cluster(['54.174.177.48'])
#session_real = cluster.connect()
#session_batch = cluster.connect()
#session_findname = cluster.connect()
#session_findloc = cluster.connect()
#session_findloc.set_keyspace("road_geoloc")
#start = time.time()
#lookup = {}
#cass = session_findloc.execute("SELECT * FROM header")
#for e in cass:
#lookup[str(e.stid)] = str(e.coord)
#print time.time() - start
zoom = 7
# -------------------------------------------------------------------------------------------------
db_lookup = pdb.connect("localhost", "root", "", "traffic") # Open database connection
cursor = db_lookup.cursor() # prepare a cursor object using cursor() method
start = time.time()
roadloc = {}
header = {}
cursor.execute("SELECT * FROM roadloc")
data = cursor.fetchall()
for e in data:
roadloc[str(e[0])] = str(e[1])
cursor.execute("SELECT * FROM header")
data = cursor.fetchall()
for e in data:
header[str(e[0])] = (e[1], str(e[2]), str(e[3]), str(e[4]), e[5])
print(time.time() - start)
db_lookup.close()
# -------------------------------------------------------------------------------------------------
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html')
@app.route('/maps')
def maps():
return render_template('index.html')
@app.route('/slideshare')
def aboutme():
co = request.cookies["session_id"]
ip = request.remote_addr + '.' + co # get the user ip and cookie
dt = str(datetime.datetime.now())
Printer(dt + ' ' + str(len(iptable)) + ' ip: ' + ip + ' ' + 'slideshare')
return render_template('slideshare.html')
@app.route('/demo')
def demo():
co = request.cookies["session_id"]
ip = request.remote_addr + '.' + co # get the user ip and cookie
dt = str(datetime.datetime.now())
Printer(dt + ' ' + str(len(iptable)) + ' ip: ' + ip + ' ' + 'video')
return render_template('demo.html')
Colors = [
"#20CA20", # green
"#FF5800", # purple
"#F50000", # red
"#941313" # dark red
]
def chooseColor(cc):
cc = int(cc)
if cc > 2000:
return Colors[3]
elif cc > 1000:
return Colors[2]
elif cc > 500:
return Colors[1]
else:
return Colors[0]
class Printer():
"""
Print things to stdout on one line dynamically
"""
def __init__(self, data):
sys.stdout.write(data.__str__() + '\r')
#sys.stdout.write("\r\x1b[K" + data.__str__())
sys.stdout.flush()
iptable = {} # create for each user
counter = 0
@app.route('/realtime_roads')
def realtime_roads():
co = request.cookies["session_id"]
ip = request.remote_addr + '.' + co # get the user ip and cookie
if ip not in iptable:
iptable[ip] = {}
global counter
counter += 1
rows = []
#session_real.set_keyspace("keyspace_realtime")
#rows = session_real.execute("SELECT * FROM mytable")
# ---------------------------------------------------------------------------------------------
db = pdb.connect("localhost", "root", "", "traffic") # Open database connection
cursor = db.cursor() # prepare a cursor object using cursor() method
cursor.execute("SELECT * FROM realtime")
rows = cursor.fetchall()
db.close()
# ---------------------------------------------------------------------------------------------
roads = []
total = 0
for row in rows:
stid = str(row[0].split('\'')[0])
cc = str(row[1])
if len(roads) >= 1500:
break
if (stid not in iptable[ip]) or ((stid in iptable[ip]) and (iptable[ip][stid] is not chooseColor(cc))):
iptable[ip][stid] = chooseColor(cc)
start = time.time()
coords = ''
if stid in roadloc:
coords = roadloc[stid]
total += time.time() - start
if len(coords) is not 0:
coord = []
listofpairs = coords.split(';')
for entry in listofpairs:
coord.append(entry.split(','))
roads.append({'name': stid, 'carcount': cc, 'coord': coord})
dt = str(datetime.datetime.now())
Printer(dt + ' ' + str(len(iptable)) + ' ip: ' + ip + ' ' + str(len(roads)))
#Printer(dt + ' ' + str(len(iptable)) + ' ip: ' + ip + ' ' + 'main page')
return jsonify(roads=roads)
#session_all = cluster.connect()
@app.route('/zoom_changed')
def add_numbers():
zoom = request.args.get('zoom', 0, type=int)
#Printer(" === " + str(zoom) + " === ")
return jsonify(result=(zoom) * 10)
@app.route('/all_roads')
def all_roads():
rows = []
#session_all.set_keyspace("road_geoloc")
#rows = session_all.execute("SELECT * FROM header")
array = []
for row in rows:
coords = row[1].split('\'')[0]
if len(coords) is not 0:
coord = []
listofpairs = coords.split(';')
for entry in listofpairs:
lat, lon = entry.split(',')
coord.append((float(lat), float(lon)))
array.append(coord)
formated = MultiLineString(array)
my_feature = Feature(geometry=formated)
coll = FeatureCollection([my_feature])
print("Show all roads")
return jsonify(coll)
@app.route("/batch/<rcid>")
def hichart(rcid):
#query = "SELECT yyyymm, carcount FROM keyspace_batch.mytable_RDD WHERE roadid = %s"
#response = session_batch.execute(query, parameters=[int(stid)])
# ---------------------------------------------------------------------------------------------
db = pdb.connect("localhost", "root", "", "traffic") # Open database connection
cursor = db.cursor() # prepare a cursor object using cursor() method
cursor.execute("SELECT yyyymm, count FROM batch WHERE rcid = %s" % str(rcid))
response = cursor.fetchall()
# ---------------------------------------------------------------------------------------------
#query = "SELECT rdn FROM station_header.header WHERE stid = %s"
#name = session_findname.execute(query, parameters=[stid])
#stname = str(name[0].rdn.split('\'')[0])
# ---------------------------------------------------------------------------------------------
tup = header[str(rcid)]
stname = tup[1] + ', ' + tup[2] + ', ' + tup[3]
# ---------------------------------------------------------------------------------------------
array = []
yyyy = []
mm = []
for val in response:
array.append(int(val[1]))
key = str(val[0])
yyyy.append(int(key[:-2]))
mm.append(int(key[4:]))
return render_template("batch_query.html", array=array, stname=stname, yyyy=yyyy, mm=mm)
@app.route("/query/<rcid>")
def query(rcid):
#query = "SELECT yyyymm, carcount FROM keyspace_batch.mytable_RDD WHERE roadid = %s"
#response = session_batch.execute(query, parameters=[int(stid)])
# ---------------------------------------------------------------------------------------------
db = pdb.connect("localhost", "root", "", "traffic") # Open database connection
cursor = db.cursor() # prepare a cursor object using cursor() method
cursor.execute("SELECT yyyymm, count FROM batch WHERE rcid = %s" % str(rcid))
response = cursor.fetchall()
# ---------------------------------------------------------------------------------------------
#query = "SELECT rdn FROM station_header.header WHERE stid = %s"
#name = session_findname.execute(query, parameters=[stid])
#stname = str(name[0].rdn.split('\'')[0])
# ---------------------------------------------------------------------------------------------
tup = header[str(rcid)]
stname = tup[1] + ', ' + tup[2] + ', ' + tup[3]
# ---------------------------------------------------------------------------------------------
array = []
yyyy = []
mm = []
for val in response:
array.append(int(val[1]))
key = str(val[0])
yyyy.append(int(key[:-2]))
mm.append(int(key[4:]))
return jsonify(array=array, stname=stname, yyyy=yyyy, mm=mm)
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)