def vote(): if request.method == 'POST': responseVote = request.form['vote'] if responseVote == "Deer": newVote = Vote(True) elif responseVote == "Bear": newVote = Vote(False) db.session.add(newVote) db.session.commit() return jsonify(response="OK") else: return jsonify(response="FAILED")
def test_count_votes_by_option(self): votation_id = self.__votation__.votation_id option_id = self.__option1.option_id for i in range(10): u = Vote(votation_id = votation_id, option_id = option_id, \ vote_key="vote_key1_" + str(i),jud_value=0) self.assertTrue(vote_dao.insert_dto(u)) for i in range(20): u = Vote(votation_id = votation_id, option_id = option_id, \ vote_key="vote_key2_" + str(i),jud_value=2) self.assertTrue(vote_dao.insert_dto(u)) db.session.commit() self.assertEqual([10, 0, 20], vote_maj_jud.count_votes_by_option( votation_id, option_id))
def test_counting_votes3(self): votation_id = self.__votation__.votation_id v = Vote(vote_key = "vote_key1", \ votation_id = votation_id, \ option_id = self.__option1.option_id, \ jud_value = 1) self.assertTrue(vote_dao.insert_dto(v)) v = Vote(vote_key = "vote_key2", \ votation_id = votation_id, \ option_id = self.__option2.option_id, \ jud_value = 1) self.assertTrue(vote_dao.insert_dto(v)) db.session.commit() d = vote_simple.counting_votes(votation_id) self.assertEqual(2, len(d.keys()))
def do_votejsonp(): response.content_type = 'application/javascript' callbackProcess = request.query.callback vote = Vote(user_id=request.query.userId, movie_id=request.query.movieId) existing = db.query(Vote).filter_by( user_id=request.query.userId).filter_by( movie_id=request.query.movieId).first() if existing != None: votes = db.query(Vote).order_by(Vote.movie_id) votelist = [] for vote in votes: votelist.append(vote.json()) jsonVotes = '"votes" : [%s]' % ','.join(votelist) return callbackProcess + '({"result": "ERROR", "message": "User has already voted for this movie.",' + jsonVotes + '})' else: db.add(vote) votes = db.query(Vote).order_by(Vote.movie_id) votelist = [] for vote in votes: votelist.append(vote.json()) jsonVotes = '"votes" : [%s]' % ','.join(votelist) # following line is to try to force the commit existing = db.query(Vote).filter_by( user_id=request.query.userId).filter_by( movie_id=request.query.movieId).first() return callbackProcess + '({"result": "OK", "message" : "Vote registered.",' + jsonVotes + '})'
def post(self, election_id): election = Election.get_by_id(long(election_id)) if election is None: raise HTTPBadRequest("Invalid election id provided.") current_user = users.get_current_user() if current_user is None: raise HTTPUnauthorized("You must be logged in to vote.") if election.HasAlreadyVoted(current_user): raise HTTPUnauthorized("You've already voted in this election.") election_active_state = election.CheckStartEndTime() if election_active_state == constants.NOT_STARTED: raise HTTPBadRequest("This election has not started yet.") elif election_active_state == constants.ENDED: raise HTTPBadRequest("This election has ended.") candidate_id = self.request.get("candidate") if candidate_id is None: raise HTTPBadRequest("No candidate was provided.") candidate = Candidate.get_by_id(long(candidate_id), parent=election) if candidate is None: raise HTTPBadRequest("Invalid candidate id provided.") voter_id = election.GenerateVoterId(current_user) Vote(parent=candidate, voter=voter_id, election=str(election.key())).put() self.NotifyChannels(election) self.render_template("webvote.html", canvote=False, message="Thanks! Your vote has been recorded", show_ads=election.ads_enabled)
def post(self): user = users.get_current_user() if not user: self.response.out.write('~!@#$%') return topic = Topic.get(self.request.get('entity')) if int(self.request.get('mark')) != 1: if not topic.votedown: topic.votedown = -1 else: topic.votedown -= 1 else: if not topic.voteup: topic.voteup = 1 else: topic.voteup += 1 topic.put() vote = Vote() vote.author = users.get_current_user() vote.topic = topic vote.mark = int(self.request.get('mark')) vote.put() memcache.delete('topic_list::latest' + user.user_id()) self.response.out.write(json_output('ok'))
def post(self, election_id, candidate_id): if self.request.get("cancel_button") == "True": self.render_template("vote.html", message="Your vote has been discarded") return election, candidate = self.ValidateElectionAndCandidate( election_id, candidate_id) current_user = users.get_current_user() if current_user is None: raise HTTPUnauthorized("You must be logged in to vote.") if election.HasAlreadyVoted(current_user): raise HTTPUnauthorized("You've already voted in this election.") election_active_state = election.CheckStartEndTime() if election_active_state == constants.NOT_STARTED: raise HTTPBadRequest("This election has not started yet.") elif election_active_state == constants.ENDED: raise HTTPBadRequest("This election has ended.") voter_id = election.GenerateVoterId(current_user) Vote(parent=candidate, voter=voter_id, election=str(election.key())).put() self.NotifyChannels(election) self.render_template( "vote.html", canvote=False, message="Thanks! Your vote for %s was registered." % candidate.name)
def vote(): allphotos = db_session.query(Photo).all() sql = """select distinct v.photo_id from votes v where v.give_vote_user_id = %s and v.value > 0;""" % ( g.user_id) upvotes = [vote[0] for vote in db_session.execute(sql)] print upvotes sql = """select distinct v.photo_id from votes v where v.give_vote_user_id = %s and v.value < 0;""" % ( g.user_id) downvotes = [vote[0] for vote in db_session.execute(sql)] if request.form: vote = request.form['vote'] photoid = request.form['photoid'] photoowner = request.form['photoowner'] v = db_session.query(Vote).filter_by(give_vote_user_id=g.user_id, photo_id=photoid).first() if not v: v = Vote(give_vote_user_id=g.user_id, photo_id=photoid, receive_vote_user_id=photoowner) db_session.add(v) p = db_session.query(Photo).filter_by(id=photoid).one() if vote == "upvote": v.value = 1 p.up_vote = Photo.up_vote + 1 elif vote == "downvote": v.value = -1 p.down_vote = Photo.down_vote + 1 db_session.commit() sql = """select distinct v.photo_id from votes v where v.give_vote_user_id = %s and v.value > 0;""" % ( g.user_id) upvotes = [vote[0] for vote in db_session.execute(sql)] sql = """select distinct v.photo_id from votes v where v.give_vote_user_id = %s and v.value < 0;""" % ( g.user_id) downvotes = [vote[0] for vote in db_session.execute(sql)] return render_template("_vote.html", u=g.user, photos=allphotos, upvotes=upvotes, downvotes=downvotes) return render_template("vote.html", u=g.user, photos=allphotos, upvotes=upvotes, downvotes=downvotes)
def submit_vote(poll_id): """This view will process a vote.""" response = request.form.get('response') user_id = session['user_id'] vote = Vote(user_id=user_id, response=response, poll_id=poll_id) db.session.add(vote) db.session.commit() return redirect(f'/poll/{poll_id}/results')
def test_counting_votes2(self): votation_id = self.__votation__.votation_id v = Vote(vote_key = "vote_key1", \ votation_id = votation_id, \ option_id = self.__option1.option_id, \ jud_value = 1) self.assertTrue(vote_dao.insert_dto(v)) db.session.commit() n = vote_simple.counting_votes(votation_id) self.assertEqual({ self.__option1.option_id: 1, }, n)
def do_vote(userid, movieid): response.content_type = 'application/json' vote = Vote(user_id=userid, movie_id=movieid) existing = db.query(Vote).filter_by(user_id=userid).filter_by( movie_id=movieid).first() if existing != None: return '{"result": "ERROR", "message": "User has already voted for this movie."}' else: db.add(vote) # following line is to try to force the commit existing = db.query(Vote).filter_by(user_id=userid).filter_by( movie_id=movieid).first() return '{"result": "OK", "message" : "Vote registered."}'
def test_counts_votes_by_votation_1(self): u = Vote(vote_key = "vote_key1", \ votation_id = self.__votation__.votation_id, \ option_id = self.__option1.option_id, \ jud_value = 0) self.assertTrue(vote_dao.insert_dto(u)) u = Vote(vote_key = "vote_key1", \ votation_id = self.__votation__.votation_id, \ option_id = self.__option2.option_id, \ jud_value = 1) self.assertTrue(vote_dao.insert_dto(u)) u = Vote(vote_key = "vote_key1", \ votation_id = self.__votation__.votation_id, \ option_id = self.__option3.option_id, \ jud_value = 2) self.assertTrue(vote_dao.insert_dto(u)) db.session.commit() actual = vote_dao.counts_votes_by_votation( self.__votation__.votation_id) expected = {self.__option1.option_id: {0:1, 1:0, 2:0}, \ self.__option2.option_id: {0:0, 1:1, 2:0}, \ self.__option3.option_id: {0:0, 1:0, 2:1} } self.assertEqual(expected, actual)
def test_insert(self): u = Vote(vote_key = "vote_key123", \ votation_id = self.__votation__.votation_id, \ option_id = self.__option1.option_id, \ jud_value = 5) self.assertTrue(vote_dao.insert_dto(u)) ar = vote_dao.load_vote_by_key("vote_key123") self.assertEqual(1, len(ar)) u1 = ar[0] self.assertIsNotNone(u1) self.assertEqual(u.votation_id, u1.votation_id) self.assertEqual(u.vote_key, u1.vote_key) self.assertEqual(u.option_id, u1.option_id) self.assertEqual(u.jud_value, u1.jud_value) vote_dao.delete_votes_by_key("vote_key123") ar = vote_dao.load_vote_by_key("vote_key123") self.assertEqual(0, len(ar))
def save_vote(votation_id, vote_key, array_judgements): option_array = option_dao.load_options_by_votation(votation_id) jud_array = judgement_dao.load_judgement_by_votation(votation_id) if len(array_judgements) != len(option_array): return False valid_jud = [] for j in jud_array: valid_jud.append(j.jud_value) i = 0 for o in option_array: if array_judgements[i] not in valid_jud: return False v = Vote(vote_key = vote_key, \ votation_id = votation_id, \ option_id = o.option_id, \ jud_value = array_judgements[i]) insert_dto(v) i += 1 return True
def setUp(self): self.bad_json = {'my_name': 'John'} self.vote = Vote("1234", "5678", 2) self.json = {'user_id': '1234', 'poll_id': '5678', 'chosen_option': 2, 'timestamp': self.vote.timestamp}
def process_vote(operation): vote = Vote() vote.author = operation[1]["author"]
def add_survey_info(student_name, student_year): vote_object = Vote(name=student_name, year=student_year) session.add(vote_object) session.commit()
def add_survey_info(person_name, person_animal): vote_object = Vote(name=person_name, animal=person_animal) session.add(vote_object) session.commit()
def socket_handler(action): if action['type'] == 'server/login': account = Account.query.filter( Account.email == action['data']['email']).first() if account and checkpw(action['data']['password'].encode('utf-8'), account.password.encode('utf-8')): game = Game.query.filter(Game.account == account, Game.finished_at == None).first() login(account, game) else: error_message(action['type'], 'Invalid login') elif action['type'] == 'server/logout': logout() elif action['type'] == 'server/register': email = action['data']['email'] password = action['data']['password'] account = Account.query.filter(Account.email == email).first() if not account: password = hashpw(password.encode('utf-8'), gensalt()) try: account = Account(email=email, password=password.decode('utf-8')) except AssertionError: error_message(action['type'], 'Invalid email address') else: commit_to_db(account) login(account) elif action['type'] == 'server/join_game': room_id = action['data']['room_id'].upper() name = action['data']['name'] game = Game.query.filter(Game.room_id == room_id, Game.finished_at == None).first() if game and not game.in_progress: player = Player.query.filter(Player.game_id == game.game_id, Player.name == name).first() if not player and len(game.players) < 8: player = Player(game=game, name=name) commit_to_db(player) join_game(game, player) elif not player and len(game.players) >= 8: error_message(action['type'], 'Game is full') else: error_message(action['type'], 'Duplicate name') elif game and game.in_progress: error_message(action['type'], 'Game already in progress') else: error_message(action['type'], 'Invalid room') elif action['type'] == 'server/leave_game': player_id = action['data']['player_id'] game_id = action['data']['game_id'] player = Player.query.filter(Player.player_id == player_id).one() game = Game.query.filter(Game.game_id == game_id).one() commit_to_db(player, delete=True) leave_game(game) elif action['type'] == 'server/create_game': account_id = action['data'] account = Account.query.filter(Account.account_id == account_id).one() active_game = Game.query.filter(Game.account == account, Game.finished_at == None).first() if not active_game: game = Game(account=account, room_id=generate_room_id()) commit_to_db(game) login(account, game) else: error_message(action['type'], 'Game {} is active'.format(active_game.room_id)) elif action['type'] == 'server/delete_game': account_id = action['data']['account_id'] game_id = action['data']['game_id'] account = Account.query.filter(Account.account_id == account_id).one() game = Game.query.filter(Game.game_id == game_id).one() close_game(game) delete_game(game) login(account) elif action['type'] == 'server/start_game': game_id = action['data']['game_id'] game = Game.query.filter(Game.game_id == game_id).one() if len(game.players) >= 3 and not game.in_progress: assign_prompts(game.players) begin_game(game) start_game(game) elif game.in_progress: error_message(action['type'], 'Game already in progress') else: error_message( action['type'], 'There must be at least 3 players in game in order to play') elif action['type'] == 'server/ready': player_id = action['data']['player_id'] node = PlayerPrompt.query.filter( PlayerPrompt.player_id == player_id).first() prompt = node.prompt answer_phase(prompt) elif action['type'] == 'server/answer': player_id = action['data']['player_id'] prompt_id = action['data']['prompt_id'] answer_text = action['data']['answer'] if answer_text == '': answer_text = 'No Answer' player = Player.query.filter(Player.player_id == player_id).one() players = [p.player_id for p in player.game.players] node = PlayerPrompt.query.filter( PlayerPrompt.prompt_id == prompt_id, PlayerPrompt.player_id.in_(players)).one() answer = Answer(player=player, node=node, text=answer_text) commit_to_db(answer) if player_id == node.player_id: next_node = PlayerPrompt.query.filter( PlayerPrompt.node_id == node.next_id).one() next_prompt = next_node.prompt answer_phase(next_prompt) elif sum([len(p.answers) - 2 for p in player.game.players]) == 0: vote_phase(player.game, node) else: answer_wait() elif action['type'] == 'server/vote': player_id = action['data']['player_id'] answer_id = action['data']['answer_id'] player = Player.query.filter(Player.player_id == player_id).one() answer = Answer.query.filter(Answer.answer_id == answer_id).one() node = answer.node game = player.game players = [p.player_id for p in game.players] nodes = PlayerPrompt.query.filter( PlayerPrompt.player_id.in_(players)).all() vote = Vote(player=player, answer=answer) commit_to_db(vote) if sum([len(n.answers[0].votes) + len(n.answers[1].votes) - \ len(players) + 2 for n in nodes]) == 0: vote_display(game, node, last=True) elif (len(node.answers[0].votes) + len(node.answers[1].votes) - \ len(players) + 2) == 0: vote_display(game, node) else: vote_wait(node)