-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
272 lines (230 loc) · 9.9 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
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
import os
from flask import Flask
from flask import render_template, url_for, flash, request, redirect, Response, session
import sqlite3
import pprint
import json
import pusher
app = Flask(__name__)
app.debug=True
db_file='/var/www/FlaskApp/FlaskApp/cluecon_elections.db'
def check_auth(username, pwd):
"""This function is called to check if a username /
password combination is valid.
"""
cfg = {'username':'admin','password':'vJCmCUrHpRdKdUHAwk'}
return username == cfg.get('username') and pwd == cfg.get('password')
def authenticate():
"""Sends a 401 response that enables basic auth"""
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'}
)
@app.route('/',methods=['GET'])
def main_route():
return redirect('/election_list')
@app.route('/election_list', methods=['GET'])
def election_list():
conn = sqlite3.connect(db_file)
conn.row_factory = sqlite3.Row
curs = conn.cursor()
curs.execute("SELECT * from election")
rows = curs.fetchall()
return render_template("election_list.html", rows=rows)
@app.route('/save_election_details', methods=['POST'])
def save_election_details():
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
msg=''
if request.method == "POST":
try:
election_name = request.form["election_name"]
election_number=request.form["election_number"]
print(election_number)
with sqlite3.connect(db_file) as con:
cur = con.cursor()
cur.execute(
"INSERT into election (election_name,sms_number) values (?,?)", [election_name,election_number])
con.commit()
msg = "Election successfully Added"
except Exception as e:
#con.rollback()
msg = "We can not add the Election to the list Error: "
print(e)
finally:
print(msg)
return redirect('/election_list')
def get_election_by_election_id(election_id):
conn = sqlite3.connect(db_file)
conn.row_factory = sqlite3.Row
curs = conn.cursor()
curs.execute("SELECT * FROM election where election_id=?",[election_id])
rows = curs.fetchone()
return rows
def get_nominee_by_election_id(election_id):
conn = sqlite3.connect(db_file)
conn.row_factory = sqlite3.Row
curs = conn.cursor()
curs.execute("SELECT * FROM nominee where election_id=?",[election_id])
rows = curs.fetchall()
return rows
def get_election_results_by_election_id(election_id):
conn = sqlite3.connect(db_file)
conn.row_factory = sqlite3.Row
curs = conn.cursor()
#curs.execute("select count(1) as vote_count, v.nominee_id, n.nominee_name, n.nominee_code from nominee n left join vote v on v.election_id =n.election_id where v.election_id=? group by v.nominee_id",[election_id])
curs.execute("select count(1) as vote_count, nominee_id from vote where election_id=? group by nominee_id",[election_id])
rows = curs.fetchall()
return rows
def get_votes_list(election_id):
votes_listt=[]
backgtound_colors=['rgba(255, 99, 132, 0.2)','rgba(54, 162, 235, 0.2)','rgba(255, 206, 86, 0.2)','rgba(75, 192, 192, 0.2)','rgba(153, 102, 255, 0.2)','rgba(255, 159, 64, 0.2)']
border_colours=['rgba(255, 99, 132, 1)','rgba(54, 162, 235, 1)','rgba(255, 206, 86, 1)','rgba(75, 192, 192, 1)','rgba(153, 102, 255, 1)','rgba(255, 159, 64, 1)']
election_result=get_election_results_by_election_id(election_id)
nominees=get_nominee_by_election_id(election_id)
i=0
for nominee in nominees:
nom={}
nom["nominee_id"]=nominee["nominee_id"]
nom["vote_count"]=0
nom["nominee_name"]=nominee["nominee_name"]
nom["nominee_code"]=nominee["nominee_code"]
nom["backgtound_color"]=backgtound_colors[i]
nom["border_colour"]=border_colours[i]
for votes_count in election_result:
if nominee["nominee_id"] == votes_count["nominee_id"]:
nom["vote_count"]=votes_count["vote_count"]
break
votes_listt.append(nom)
i=i+1
if (len(backgtound_colors) == i):
i=0
return votes_listt
@app.route('/view_election/<election_id>',methods = ["GET"])
def view_election(election_id):
votes_list=get_votes_list(election_id)
chart_data=""
background_colors=""
for vote in votes_list:
chart_data = chart_data + vote['nominee_name'] + "@@" + str(vote['vote_count']) + ","
background_colors= background_colors + vote['backgtound_color'] + "@@" + vote['border_colour'] + "$$"
print(background_colors)
return render_template("election_details.html",election_details=get_election_by_election_id(election_id),election_id=election_id,votes_list=votes_list,chart_data=chart_data,background_colors=background_colors)
@app.route("/delete_election/<election_id>",methods = ["POST"])
def delete_delete_election(election_id):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
msg="POST request"
try:
with sqlite3.connect(db_file) as con:
cur = con.cursor()
cur.execute("DELETE FROM election where election_id=?",[election_id])
con.commit()
msg = "Election deleted sucessfully"
except Exception as e:
msg = "We can not delete the Election from the list Error: " + e
finally:
con.close()
return redirect(url_for('election_list'))
@app.route("/save_nominee_details/<election_id>",methods = ["POST"])
def save_nominee_details(election_id):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
msg=''
if request.method == "POST":
try:
nominee_name = request.form["nominee_name"]
nominee_code=request.form["nominee_code"]
with sqlite3.connect(db_file) as con:
cur = con.cursor()
cur.execute(
"INSERT into nominee (nominee_name,nominee_code,election_id) values (?,?,?)", [nominee_name,nominee_code.upper().strip(),election_id])
con.commit()
msg = "Nominee successfully Added"
except Exception as e:
#con.rollback()
msg = "We can not add the Election to the list Error: "
print(e)
finally:
print(msg)
return redirect('/view_election/'+election_id)
def get_nominees_by_enection_id_and_nominee_code(body,election_id):
conn = sqlite3.connect(db_file)
conn.row_factory = sqlite3.Row
curs = conn.cursor()
curs.execute("SELECT * FROM nominee where election_id=? and nominee_code=?",[election_id,body.upper().strip()])
row = curs.fetchone()
return row
def get_election_by_number(to_number):
conn = sqlite3.connect(db_file)
conn.row_factory = sqlite3.Row
curs = conn.cursor()
curs.execute("SELECT * FROM election where sms_number=?",[to_number])
row = curs.fetchone()
return row
def check_already_voted(form_data,election_id):
conn = sqlite3.connect(db_file)
conn.row_factory = sqlite3.Row
curs = conn.cursor()
curs.execute("SELECT * FROM vote where to_number=? and from_number=? and election_id=?",[form_data['To'],form_data['From'],election_id])
row = curs.fetchone()
return row
def pusn_to_websocket(election_id,to_number):
votes_list=get_votes_list(election_id)
chart_data=""
background_colors=""
for vote in votes_list:
chart_data = chart_data + vote['nominee_code'] + "@@" + str(vote['vote_count']) + ","
pusher_client = pusher.Pusher(
app_id='1284957',
key='e4229bc4dffdc9ccb3eb',
secret='e01ea4764d7f4c9b99f8',
cluster='ap2',
ssl=False
)
pusher_client.trigger('sharp-cow-343', to_number, {'message': chart_data})
@app.route("/cluecon_election_webhook",methods = ["POST"])
def cluecon_election_webhook():
print(request.form)
election_details=get_election_by_number(request.form['To'])
xml="<Response/>"
if election_details == None:
xml="<Response><Message>Not a election number</Message></Response>"
else:
vote_for=get_nominees_by_enection_id_and_nominee_code(request.form['Body'],election_details[0])
nominee_id=None
if vote_for==None:
nominees=get_nominee_by_election_id(election_details[0])
xml="<Response><Message>You enterd an invalid code,"
for row in nominees:
xml=xml +" To vote " + row["nominee_name"] + " reply with code :" + row["nominee_code"] + "\n"
xml=xml+"</Message></Response>"
else:
already_voted=check_already_voted(request.form,election_details[0])
try:
if already_voted == None:
with sqlite3.connect(db_file) as con:
cur = con.cursor()
cur.execute("INSERT into vote (to_number,from_number,body,sid,nominee_id,election_id) values (?,?,?,?,?,?)",
[request.form['To'],
request.form['From'],
request.form['Body'],
request.form['MessageSid'],
vote_for[0],election_details[0]])
con.commit()
xml="<Response><Message>Thank you for your vote</Message></Response>"
pusn_to_websocket(election_details[0],request.form['To'])
else:
xml="<Response><Message>Your vote aleady registred for "+ already_voted[3] + "</Message></Response>"
except Exception as e:
#con.rollback()
print(e)
return Response(xml, mimetype='text/xml')
SECRET_KEY = os.urandom(32)
app.config['SECRET_KEY'] = SECRET_KEY
if __name__ == "__main__":
app.run(host='0.0.0.0',port=8031,threaded=True)