def getElections(): timestamp = getDBTimestamp(getCurTime()) #get today in mysql datetime format cur = db.connection.cursor() cur.execute("SELECT election_id, name FROM elections WHERE end_date <= %s", [timestamp]) results = cur.fetchall() #populate our data structure prior_elections = [] # list of tuples (eid, name) for (eid, name) in results: prior_elections.append((eid,name)) return prior_elections
def validElectionID(num): if num.isdigit(): timestamp = getDBTimestamp(getCurTime()) #today's timestamp #make sure value of num references a valid election that has ended cur = db.connection.cursor() cur.execute("SELECT * FROM elections WHERE election_id = %s AND end_date <= %s", [num, timestamp]) result = cur.fetchall() if len(result) > 0: return True return False
def vote(election, candidate=None, voted=True, userid=""): #when we create an election, we need to create the corresponding rows in electionData #because this function will assume they're just there mutex.acquire() #get the mutex try: #prep for mysql stuff later on timestamp = getDBTimestamp(getCurTime()) #get a mysql datetime value of the current datetime cur = db.connection.cursor() #get our mysql cursor #if user already voted in this election return false #we're checking this before calling this function so we should be able to remove this if votedAlready(election, userid): return False #update mysql db if voted: #should we wrap all of the mysql statements in try/catch blocks in case there's an error? #update electionData by adding 1 to the vote count for the given condition cur.execute("UPDATE electionData SET num_votes=num_votes+1 WHERE election_id = %s" + " AND candidate_id = %s", [election, candidate]) db.connection.commit() result = cur.fetchall() #add voter to the voterHistory table with voted=1 cur.execute("INSERT INTO voterHistory (election_id, voter_id, time_stamp, voted) VALUES" + " (%s, %s, %s, 1)", [election, userid, timestamp]) db.connection.commit() result = cur.fetchall() return True else: #failed vote #add the vote to voterHistory table but set the voted value to false cur.execute("INSERT INTO voterHistory (election_id, voter_id, time_stamp, voted) VALUES" + " (%s, %s, %s, 0)'", [election, userid, timestamp]) result = cur.fetchall() except: #in case we error, we want internal server error or debugger raise finally: #no matter what, release mutex mutex.release() return False