def vote(request, id): """ Add a vote for a feedback message, but not twice from the same IP. """ referer = request.META.get('HTTP_REFERER', '/feedback/') redirect = HttpResponseRedirect(referer) # Check if the selected feedback exists. feedback = Feedback.get_by_id(int(id)) if feedback is None: logging.debug("Feedback '%s' not found." % id) return redirect # Check if this feedback was posted from the same IP. ip = request.META.get('REMOTE_ADDR', '0.0.0.0') if feedback.ip == ip: logging.debug("Feedback '%s' was posted from the same IP." % id) return redirect # Check if this IP has already voted for this feedback. already = Vote.all().filter('feedback', feedback).filter('ip', ip).count() if already: logging.debug("Feedback '%s' was already voted %d times from this IP." % (id, already)) return redirect # Register this vote to prevent double voting. vote = Vote(feedback=feedback, ip=ip) vote.put() # Increase the points for this feedback. feedback.points += 1 feedback.put() return redirect
def GET(self, seq, pos): count = Vote.count(web.ctx.game.id, seq, pos) comments = Comment.details(web.ctx.game.id, seq, pos) votes = Vote.details(web.ctx.game.id, seq, pos) all_comments = {} for c in comments: all_comments[(c.rating, c.name)] = (c.notes, 'comment') for v in votes: all_comments[(v.rating, v.name)] = (v.notes, 'vote') sorted_comments = sorted( all_comments.iteritems(), key=lambda ((rating, name), _): -rating, ) return json.dumps({ 'display_pos': Pretty.pos(pos), 'count': count, 'votes': [ { 'name': name, 'rating': Pretty.rating(rating), 'notes': notes, 'type': note_type, } for (rating, name), (notes, note_type) in sorted_comments ], })
def vote(): print "We're here!" if request.form.get("vote") == "up": # expression == returns True, if != returns False vote_input = 1 # upvote else: vote_input = -1 # downvote post_id = request.form.get("post_id") vote = Vote.query.filter_by(post_id=post_id, user_id=g.user.id).first() if vote is None: vote = Vote(post_id=post_id, user_id=g.user.id, vote=vote_input) db.session.add(vote) db.session.commit() db.session.refresh(vote) else: vote.vote = vote_input db.session.commit() vote.post.score += vote_input # TypeError: unsupported operand type(s) for +=: 'NoneType' and 'int' db.session.commit() # if vote, Post(score += 1) # manual in sql: UPDATE post SET score = (SELECT SUM(vote) FROM vote WHERE post_id = Post.id); # change upvote to green if successful? # if user upvotes a post, can change to downvote/cancel how? # see unique constraint in models.Vote > no that didn't work, see \d vote UNIQUE in psql return "Vote recorded!"
def vote(definition_id): body = request.get_json() try: definition = db.session.query(Definition).filter_by(id=definition_id).one() except NoResultFound as ex: return jsonify({'error': 'Definition does not exist'}) try: user = db.session.query(User).filter_by(twitter_id=body.get('userId')).one() except NoResultFound as ex: return jsonify({'error': 'Auth Error'}) posted_auth_token = body.get('authToken') token = encode_value( user.oauth_token, app.config.get('AUTH_SALT') ) if token != posted_auth_token: return jsonify({'error': 'Auth Error'}) try: vote = db.session.query(Vote).filter_by(definition_id=definition.id).\ filter_by(user_id=user.id).one() except NoResultFound as ex: vote = Vote() vote.definition_id = definition.id vote.user_id = user.id vote.vote = 1 if body.get('isUpvote') else -1 db.session.add(vote) db.session.commit() return jsonify({'vote': { 'id': vote.id}})
def post(self, post_id): session = get_current_session() if session.has_key('user'): message = helper.sanitizeHtml(self.request.get('message')) user = session['user'] key = self.request.get('comment_key') if len(message) > 0 and key == keys.comment_key: try: post = Post.all().filter('nice_url =', helper.parse_post_id( post_id ) ).get() if post == None: #If for some reason the post doesn't have a nice url, we try the id. This is also the case of all old stories post = db.get( helper.parse_post_id( post_id ) ) post.remove_from_memcache() comment = Comment(message=message,user=user,post=post) comment.put() helper.killmetrics("Comment","Root", "posted", session, "",self) vote = Vote(user=user, comment=comment, target_user=user) vote.put() Notification.create_notification_for_comment_and_user(comment,post.user) self.redirect('/noticia/' + post_id) except db.BadKeyError: self.redirect('/') else: self.redirect('/noticia/' + post_id) else: self.redirect('/login')
def voted(): vote_form = Vote(request.form) # if form was submitted and it is valid... if request.method == "POST" and vote_form.validate(): # get form data - create new idea vote = models.Vote() vote.bestoverall = request.form.get('bestoverall') vote.transformation = request.form.get('transformation') vote.arrestable = request.form.get('arrestable') vote.keepit = request.form.get('keepit') VoteCasted=models.VoteCasted() VoteCasted.bestoverall=vote.bestoverall VoteCasted.transformation=vote.transformation VoteCasted.arrestable=vote.arrestable VoteCasted.keepit=vote.keepit VoteCasted.save() # app.logger.debug(templateData) return render_template("voted.html") else: templateData = { 'form' : vote_form } return render_template("voted.html", **templateData)
def process_vote(post_id): """this is the function that process users' votes, so it updates the database and refresh the post-details page to show the updated votes and vote allocation""" if session.get('loggedin', None): choice_id = request.form.get("choice_id") user_id = session['loggedin'] post = Post.get_post_by_id(post_id) previous_vote = post.check_choice_on_post_by_user_id(user_id) if previous_vote: # if there is a previous vote, compare to the new vote see if they pointed to the same choice, update vote if previous_vote != choice_id: vote_id = Vote.get_vote_by_post_and_user_id(post.post_id, user_id) Vote.update_vote(vote_id, choice_id) else: Vote.create(user_id=user_id, choice_id=choice_id) # if it's first time vote, create a new vote vote_dict, total_votes, chart_dict = post.count_votes() bar_chart_gender = post.bar_chart_gender() geo_chart_location = post.count_votes_by_location() bar_chart_age = post.count_votes_by_age() total_votes_percent = {} for vote in vote_dict: total_votes_percent[vote] = float(vote_dict[vote]) / total_votes return json.dumps( [vote_dict, total_votes_percent, total_votes, chart_dict, bar_chart_gender, geo_chart_location, bar_chart_age]) else: return json.dumps("undefined")
def vote(request, new_vote): response = "" error = "" status = 201 if not request.user.is_authenticated(): error = "Must be logged in" status = 403 elif request.method == "POST": data = request.POST r = Review.objects.get(pk=data["review_pk"]) try: prev_vote_obj = Vote.objects.get(review=r.pk, user=request.user) prev_vote = prev_vote_obj.vote if new_vote != prev_vote: prev_vote_obj.delete() r.up_down_rank += new_vote except ObjectDoesNotExist: r.up_down_rank += new_vote v = Vote(user=request.user, review=r, vote=new_vote) v.save() r.save() response = serialize([r]) else: error += "No POST data in request.\n" status = 415 return HttpResponse(package_error(response, error), status=status)
def post_vote(room_code): sessid = request.cookies.get("sessid") you = Player.select(Player, Room).join(Room).where(Player.sessid == sessid, Room.code == room_code).get() room = you.room vote = request.params["vote"] mission_id = request.params["missionId"] mission = Mission.get(Mission.id == mission_id, Mission.room == room) Vote.insert(player=you, mission=mission, vote=vote).execute() votes = Vote.select(Vote, Player).join(Player).where(Vote.mission == mission).execute() if votes.count == room.size: upvotes = sum(1 for v in votes if v.vote == "yes") agreed = True if (upvotes * 2 > votes.count) else False votes_message_data = { "votes": [ {"player": {"id": vote.player.id, "name": vote.player.name}, "vote": vote.vote} for vote in votes ], "agreed": agreed, } messages = [Msg("votes", votes_message_data)] if agreed: room.phase = Room.PHASE_MISSION room.save() else: room.phase = Room.PHASE_TEAM_BUILD leader = next_leader(room) leader_message_data = {"leader": {"id": leader.id, "name": leader.name}} messages.append(Msg("leader", leader_message_data)) post_message(messages, room=room)
def api_poll_vote(request): api_result = {"api": "poll_vote", "status": "success"} try: token = request.GET["token"] user = get_user_from_token(token) if not user: api_result["status"] = "failure" api_result["error"] = "user not found" else: question_id = request.GET["id"] choice_id = request.GET["choice"] question = Question.objects.get(pk=question_id) choice = Choice.objects.get(pk=choice_id) # user vote Vote.give_vote(user, question, choice) api_result["mychoice"] = choice.choice_text api_result["choices"] = [ c.choice_text[:10] + ".." if len(c.choice_text) > 10 else c.choice_text for c in question.choice_set.all() ] api_result["votes"] = [c.votes for c in question.choice_set.all()] except Exception as e: api_result["status"] = "failure" api_result["error"] = e.message pass return JsonResponse(api_result)
def update(self, votes, addCat): # Delete the old votes and replace them with the request data. # This avoids cases where the form data doesn't match the # current database (e.g. from the back button or a cloned # window). if self.ballot: db.delete(votes) ballot = self.ballot else: ballot = Ballot(voter=self.voter, year=self.year) ballot.anonymous = bool(self.request.get('anonymous')) ballot.preamble = self.request.get('preamble') ballot.postamble = self.request.get('postamble') numVotes = dict() for cat in Ballot.categories: numVotes[cat] = int(self.request.get(cat + 's')) ballot.honorable = numVotes['honorable'] if addCat == 'honorable': ballot.honorable += 10 ballot.notable = numVotes['notable'] if addCat == 'notable': ballot.notable += 10 ballot.put() for cat in Ballot.categories: for rank in range(1, numVotes[cat]+1): artist = self.request.get('%s%dartist' % (cat, rank)) title = self.request.get('%s%dtitle' % (cat, rank)) comments = self.request.get('%s%dcomments' % (cat, rank)) if artist or title or comments: vote = Vote(parent=ballot, ballot=ballot, category=cat, rank=rank, artist=artist, title=title, comments=comments) vote.put()
def vote(request): comment_id = request.POST['comment_id'] value = request.POST['value'] comment = Comment.objects.get(pk=comment_id) try: vote = Vote.objects.get(comment=comment, author=request.user) vote.value = value except Vote.DoesNotExist: vote = Vote(comment=comment, value=value, author=request.user) vote.save() # Reload the comment to make sure vote counts are up to date comment = Comment.objects.get(pk=comment_id) try: task = Task.objects.get(chunk=comment.chunk, reviewer=request.user) if task.status == 'N' or task.status == 'O': task.mark_as('S') except Task.DoesNotExist: pass response_json = json.dumps({ 'comment_id': comment_id, 'upvote_count': comment.upvote_count, 'downvote_count': comment.downvote_count, }) return HttpResponse(response_json, mimetype='application/javascript')
def vote_post(request, post_id, mode='plain'): post_id = int(post_id) post = get_object_or_404(Post, id=post_id) kwargs = dict(post=post) if not mode in ['plain', 'ajax'] or '_pv_%d' % post_id in request.session: return HttpResponseRedirect(post.get_absolute_url()) if request.user.is_authenticated(): kwargs['user'] = request.user else: kwargs['ip'] = request.META['REMOTE_ADDR'] try: Vote.objects.get(**kwargs) output_ajax = 0 except Vote.DoesNotExist: new_vote = Vote(**kwargs) new_vote.save() post.nb_votes += 1 post.save() request.session['_pv_%d' % post_id] = True request.session.set_expiry(timedelta(days=365)) output_ajax = 1 if mode == 'ajax': return HttpResponse(output_ajax) else: return HttpResponseRedirect(post.get_absolute_url())
def polling_station_vote(ballot_id): ballot = db.session.query(Ballot).get(ballot_id) if ballot is None: abort(404) permit_voting(ballot) input_options = pickle.loads(request.form["input_options_data"]) try: validate_options(input_options, ballot) except ValidationError as e: flash(unicode(e), "danger") return redirect(url_for('polling_station_item', ballot_id=ballot_id)) except ValueError as e: flash(u"Některý z hlasů má neplatnou hodnotu", "danger") return redirect(url_for('polling_station_item', ballot_id=ballot_id)) try: vote_timestamp = session.get( "vote_timestamp_{}".format(ballot_id), False) if not vote_timestamp: raise ValidationError() hash_base = compute_hash_base(ballot_id, g.user.id, input_options, vote_timestamp) hash_salt = request.form["hash_salt"] h = hashlib.sha1() h.update(hash_base.encode("utf-8")) h.update(hash_salt.encode("utf-8")) hash_digest = h.hexdigest() except Exception as e: flash(u"Chyba při výpočtu kontrolního řetězce", "danger") return redirect(url_for('polling_station_item', ballot_id=ballot_id)) for (option_id, value) in input_options.items(): vote = Vote() vote.ballot_option_id = option_id vote.value = value vote.hash_digest = hash_digest db.session.add(vote) voter = Voter() voter.ballot_id = ballot_id voter.name = g.user.name voter.email = g.user.email voter.person_id = g.user.id voter.voted_at = datetime.datetime.now() voter.remote_addr = request.remote_addr voter.user_agent = request.user_agent.string db.session.add(voter) send_mail = "send_confirmation_email" in request.form email_body = send_vote_confirmation(ballot, voter, hash_digest, hash_salt, vote_timestamp, send_mail) db.session.commit() return render_template( 'polling_station_vote.html', ballot=ballot, hash_digest=hash_digest, email_body=email_body, really_send=send_mail)
def create_subject(topic, group, deadline, votetype, options, creator): if not get_group(group): raise Exception('Group not exist') if votetype not in ['0', '1']: raise Exception('Vote type error') options = [o for o in options if o] if not options: raise Exception('No options') subject = Subject.create(topic, deadline, votetype, group, creator) for option in options: Vote.create(subject.id, option)
def vote(request, id_num): vf = VoteForm(request.POST or None) post = get_object_or_404(Post, pk=id_num) if vf.is_valid() and request.user.is_authenticated(): user = request.user prev_vote = Vote.objects.filter(user=user, parent_post=post.parent,) if prev_vote.exists(): prev_vote.delete() messages.warning(request, 'Changing your vote because you already voted on some child of the parent post') vote = Vote(post=post, parent_post=post.parent, user=user) vote.save() return HttpResponseRedirect(request.META["HTTP_REFERER"])
def prefetch_posts_list(posts): prefetch_refprops(posts, Post.user) posts_keys = [str(post.key()) for post in posts] # get user, if no user, all already_voted = no session = get_current_session() if session.has_key('user'): user = session['user'] memcache_voted_keys = ["vp_" + post_key + "_" + str(user.key()) for post_key in posts_keys] memcache_voted = memcache.get_multi(memcache_voted_keys) memcache_to_add = {} for post in posts: vote_value = memcache_voted.get("vp_" + str(post.key()) + "_" +str(user.key())) if vote_value is not None: post.prefetched_already_voted = vote_value == 1 else: vote = Vote.all().filter("user ="******"post =", post).fetch(1) memcache_to_add["vp_" + str(post.key()) + "_" + str(user.key())] = len(vote) post.prefetched_already_voted = len(vote) == 1 if memcache_to_add.keys(): memcache.add_multi(memcache_to_add, 3600) else: for post in posts: post.prefetched_already_voted = False # now the sum_votes memcache_sum_votes_keys = ["p_" + post_key for post_key in posts_keys] memcache_sum_votes = memcache.get_multi(memcache_sum_votes_keys) memcache_to_add = {} for post in posts: sum_votes_value = memcache_sum_votes.get("p_" + str(post.key())) if sum_votes_value is not None: post.prefetched_sum_votes = sum_votes_value else: sum_votes = Vote.all().filter("post =", post).count() memcache_to_add["p_" + str(post.key())] = sum_votes post.prefetched_sum_votes = sum_votes if memcache_to_add.keys(): memcache.add_multi(memcache_to_add, 3600) # finally we get all the comment count from memcache memcache_comment_count_keys = ["pc_" + post_key for post_key in posts_keys] memcache_comment_count = memcache.get_multi(memcache_comment_count_keys) memcache_to_add = {} for post in posts: comment_count = memcache_comment_count.get("pc_" + str(post.key())) if comment_count is not None: post.cached_comment_count = comment_count else: comment_count = post.comments.count() memcache_to_add["pc_" + str(post.key())] = comment_count post.cached_comment_count = comment_count if memcache_to_add.keys(): memcache.add_multi(memcache_to_add, 3600)
def test_votes(self): u = User('user', 'applez1') c = Community('Powerlifting', None, None, None, None) post = Posts('This is a Title', 'This is a body', author=u, community=c) comment1 = Comments("This is a comment", author=u, post=post) v = Vote(u) self.assertEqual(u, v.user) v = Vote(u, post=post) self.assertEqual(v.post, post) v = Vote(u, comment=comment1) self.assertEqual(v.comment, comment1) v.vote(u, post, 1, post) self.assertEqual(post.value, 1)
def handle_call_request(request): if request.method != 'POST': msg = "Only POST Request Allowed" else: # dont accept requests from any other system if request.META['REMOTE_ADDR'] not in settings.ALLOWED_IPS: msg = "IP not allowed" else: to_no = get_post_param(request, 'To') from_no = get_post_param(request, 'From') if from_no == "": msg = "No Number Recieved" else: direction = get_post_param(request, 'Direction') if not (to_no == settings.DID and direction == 'inbound'): msg = "Invalid Direction" else: # get current speaker try: speaker = get_object_or_404(Speaker, currently_speaking=True) except Http404: speaker = None if speaker is None: msg = "No Current Speaker" else: # check if this vote is already considered try: vote = get_object_or_404(Vote, speaker=speaker, phone_no=from_no) except Http404: vote = None if vote is not None: msg = "Duplicate Vote" else: speaker.total_votes = speaker.total_votes + 1 speaker.save() vote_dict={ "speaker": speaker, "phone_no": from_no, } vote_obj= Vote(**vote_dict) vote_obj.save() tweet_text = '''Got a vote for "%s" speaking on "%s" from the number "+%s" #cluecon''' % (speaker.name, speaker.talk_name, mask_phone(from_no)) if not post_tweet(tweet_text): pass # do some logging here # return success response = create_success_restxml() return HttpResponse(response, mimetype='text/xml') return HttpResponse(create_fail_restxml(msg), mimetype='text/xml')
def post(): values = {} vote_value = request.form['vote'] vote = Vote() for item in request.form.getlist('value[]'): if vote.get_vote_title(item) is not None: values[item] = vote.get_vote_title(item) elif int(item) == Vote.CUSTOM_VOTE_ID and vote_value: values[item] = vote_value if values: # add vote vote.ip = request.remote_addr vote.votes = values try: vote_current = Vote.objects(ip=request.remote_addr, created_at__gte=(datetime.datetime.now() - datetime.timedelta(minutes=15))) if vote_current: raise ValueError("You've already voted!") vote.save() suffix = VoteView.ordinal(len(Vote.objects)) return jsonify({'status': 'ok', 'message': 'Thank your for voting! You are the %s fan of python' % suffix}) except ValueError as e: return jsonify({'status': 'error', 'message': e.message}) except Exception: return jsonify({'status': 'error', 'message': 'Error while saving vote. Sorry :('}) else: return jsonify({'status': 'error', 'message': 'Choose any option to vote'})
def POST(self): form = VoteForm() if not form.validates(): raise web.notfound(form.note) if not web.ctx.game.your_turn: raise web.notfound("It's not your turn!") Vote.insert_or_update( ('game_id', 'user_id', 'seq'), game_id=web.ctx.game.id, user_id=web.ctx.user.id, seq=web.ctx.game.current_seq, move=form.d.pos, notes=form.d.notes, ip_address=web.ctx.ip, )
def increase_vote(item, owner, cur_votes): if item == None: return cur_votes # Check duplicate q = db.GqlQuery("SELECT * FROM Vote WHERE item = :1 AND owner = :2", item, owner) if q.count() > 0: ret = """<span id="vote_result">%d</span> <span id="vote_message" style="color: #666666;">(已推薦過)</span>""" % (cur_votes, ) return ret vote = Vote(owner=owner, item=item) vote.put() ret = """<span id="vote_result" style="color: #EB7F00; text-weight: bold">%d</span>""" % (item.vote_set.count(), ) return ret
def vote(request, id_num): vf = VoteForm(request.POST or None) post = get_object_or_404(Post, pk=id_num) if request.method == "POST" and vf.is_valid(): if request.user.is_authenticated(): user = request.user else: user = User.objects.get(username="******") vote = Vote(post=post, user=user, ip=request.META["REMOTE_ADDR"]) vote.save() return HttpResponseRedirect(request.META["HTTP_REFERER"]) return render_to_response("vote.html", {"form": vf}, context_instance=RequestContext(request))
def do_vote(querier, kind, instance_id, vote=1): """ Realiza un voto a un comentarion :param instance_id: ID del objeto a comentar :type instance_id: :class:`long` :param vote: valoracion del voto :type vote: :class:`integer` """ if not kind in ['Event', 'List', 'Comment']: return None vote = int(vote) if vote > 1 or vote < -1: return False from geoalert.models import Event from geolist.models import List from geovote.models import Comment try: obj = eval(kind).objects.get_by_id(instance_id) except: return None if obj is None: return None if obj.__class__.user.get_value_for_datastore(obj) != querier.key(): if hasattr(obj, '_vis'): if obj._is_private(): return None elif obj._is_shared() and not obj.user_invited(querier): return None else: return None else: # no se puede votar lo de uno mismo return None vote = Vote.do_vote(user=querier, instance=obj, count=vote) return {'vote': vote, 'votes': _get_vote(obj.key())}
def get(self, boker_id): boker = Boker.get_by_id(int(boker_id)) if boker: deferred.defer(update_num_view, str(boker.key())) # Check post type, Video or Photo if boker.video_id and boker.video_source: self.template = 'video.html' if self.current_user is not None: user = User.get_by_key_name(self.current_user['id']) can_like = not Like.already_like(user, boker) else: can_like = False else: active_contest = Contest.active_contest() if active_contest: is_nominee = Contest.is_nominee(boker) if self.current_user is not None: user = User.get_by_key_name(self.current_user['id']) can_vote = not Vote.already_vote(user) can_like = not Like.already_like(user, boker) else: can_vote = False can_like = False querystring = self.request.GET return self.render_response(self.template, locals()) else: self.abort(404)
def rawPost(self, ballotID, voteID): vote = self.getVote(ballotID, voteID) id = self.request.get('release.id', default_value=None) mbid = self.request.get('release.mbid', default_value=None) if id: vote.release = db.Key.from_path(Release.kind(), int(id)) elif mbid: vote.release = Release.get(mbid) else: id = self.request.get('artist.id', default_value=None) mbid = self.request.get('artist.mbid', default_value=None) if id: artist = db.Key.from_path(Artist.kind(), int(id)) elif mbid: artist = Artist.get(mbid) else: artist = Artist(name=self.request.get('artist'), sortname=self.request.get('sortname')) artisturl = self.request.get('artisturl', default_value=None) if artisturl: artist.url = artisturl artist.put() release = Release(artist=artist, title=self.request.get('title')) releaseurl = self.request.get('releaseurl', default_value=None) if releaseurl: release.url = releaseurl release.put() vote.release = release vote.put() next = Vote.gql('WHERE release = :1 ORDER BY artist', None).get() if next: key = next.key() self.redirect('../%d/%d' % (key.parent().id(), key.id())) else: self.redirect('../..')
def GET(self, seq=None): now = time.localtime() hours_left = 23 - now.tm_hour mins_left = 59 - now.tm_min time_left = "%02d:%02d" % (hours_left, mins_left) current_seq = web.ctx.game.current_seq if seq is None: seq = current_seq else: seq = int(seq) if web.ctx.game.your_turn or seq != current_seq: vote_counts = Vote.summary(web.ctx.game.id, seq) top_votes = [ { 'pos': vote.move, 'count': int(vote.cnt), 'label': vote.move != 'tt' and chr(i + 65) or 'Pass', } for i, vote in enumerate(vote_counts) ] comment_counts = Comment.summary(web.ctx.game.id, seq) comments = [ { 'pos': comment.move, } for i, comment in enumerate(comment_counts) ] else: top_votes = [] comments = [] turn = seq % 2 == 1 and "Black's turn." or "White's turn." game_state = GameState.get( game_id=web.ctx.game.id, seq=seq - 1, ) system_message = SystemMessage.get() if system_message: system_message = system_message.message return json.dumps({ 'id': web.ctx.game.id, 'seq': seq, 'turn': turn, 'current_seq': current_seq, 'board_size': 19, 'board': json.loads(game_state.board), 'last_move': game_state.move, 'illegal': json.loads(game_state.illegal), 'black_captures': game_state.black_captures, 'white_captures': game_state.white_captures, 'votes': top_votes, 'comments': comments, 'time_left': time_left, 'system_message': system_message, })
def get(self, post_id): session = get_current_session() if session.has_key("user"): user = session["user"] try: post = db.get(post_id) if not post.already_voted(): vote = Vote(user=user, post=post, target_user=post.user) vote.put() post.remove_from_memcache() post.user.remove_from_memcache() self.response.out.write("Ok") else: self.response.out.write("No") except db.BadValueError: self.response.out.write("Bad") else: self.response.out.write("Bad")
def get(self,comment_id): session = get_current_session() if session.has_key('user'): user = session['user'] try: comment = db.get(comment_id) if not comment.already_voted(): vote = Vote(user=user, comment=comment, target_user=comment.user) vote.put() comment.remove_from_memcache() comment.user.remove_from_memcache() self.response.out.write('Ok') else: self.response.out.write('No') except db.BadValueError: self.response.out.write('Bad') else: self.response.out.write('Bad')
def get(self, year): poll = Poll.get(year) if not poll: self.response.out.write('No poll for ' + year + '.') return unc = [] for b in poll.ballots(): unc.extend(Vote.gql('WHERE ballot = :1 AND release = :2', b, None)) unc.sort(key=lambda v: v.artist.lower()) self.render('admin.html', poll=poll, unc=unc)
db.drop_all() db.create_all() me = User.create(email='*****@*****.**', name='david', password='******') kynsi = User.create(email='*****@*****.**', name='kynsi', password='******') chris = User.create(email='*****@*****.**', name='chris', password='******') tori = User.create(email='*****@*****.**', name='tori', password='******') valentine = Party.create(address="12248 Hunter's Knoll Dr", city="Burleson", state="Texas", zip_code=76028, leader_id=me.id, name="Valentine's day dinner") Resturaunt.get_resturaunts(party_id=valentine.id) valentine.add_member(kynsi.id) valentine.add_member(chris.id) valentine.add_member(tori.id) for member in valentine.members: for resturaunt in valentine.resturaunts: vote = True if random.randint(0, 1) else False new_vote = Vote.vote(member=member, party_id=valentine.id, resturaunt_id=resturaunt.id, yay=vote)
def get(self): migration_name = self.request.get("m") if migration_name == '1': self.set_votes_up_down() self.response.out.write("1-items OK") votes = Vote.query() for v in votes: dirty = False try: if v.vote == True: v.vote = 1 dirty = True except: v.vote = 1 dirty = True if dirty: v.put() self.response.out.write("1-votes OK") return elif migration_name == '2': self.move_comment_to_vote() self.response.out.write("2-vote comments OK") elif migration_name == '3': self.at_least_one_vote_per_item() self.response.out.write("3-vote totals OK") elif migration_name == '4': self.one_vote_per_item() self.response.out.write("4-latLng OK") elif migration_name == '5': self.votes_down_to_abs() self.response.out.write("5-+ve votes OK") elif migration_name == "6": self.add_geohash() self.response.out.write("6 - geohash added OK") elif migration_name == "7": self.recalc_votes_totals() self.response.out.write("7 - votes re-totaled OK") elif migration_name == "8": self.add_google_img_if_missing() self.response.out.write("8 - images got from google OK") elif migration_name == "9": self.add_phone_numbers() self.response.out.write("9 - phone nos got from google OK") elif migration_name == "10": self.item_title_to_StringProperty() self.response.out.write("10 - title becomes place_name StringProp OK") elif migration_name == "11": self.remote_urls_to_blobs() self.response.out.write("11 - images got from google into db OK") elif migration_name == "remove_orphan_votes": self.remove_orphan_votes() self.response.out.write(json.dumps({ 'status':'OK', 'detail':'12 - votes clean'})) elif migration_name == "13": self.add_websites() self.response.out.write("13 - websites got from google OK") elif migration_name == "14": self.add_edited() self.response.out.write("14 - last edit times added") elif migration_name == "add-blocked": self.add_blocked_to_user() self.response.out.write("User blocked - added") elif migration_name == "reset-vote-times": self.set_vote_time_to_now() self.response.out.write("Vote Times Reset") elif migration_name == "add-cuisines": self.add_cuisines() self.response.out.write("Vote Times Reset") elif migration_name == "add-addresses": self.add_addresses() self.response.out.write("Addresses Added") elif migration_name == "add-cuisine": self.add_new_cuisine() self.response.out.write("Cuisine added") elif migration_name == "set-vote-value": self.change_votes_to_votevalue() self.response.out.write("Vote values added") elif migration_name == "reset-items-json": self.wipe_item_json() self.response.out.write("Places reset") elif migration_name == "change-votes-to-4-dot": self.change_votes_to_4_dot() self.response.out.write("Places reset") elif migration_name == "add_google_data": self.add_google_data_if_missing() self.response.out.write("Google data added") elif migration_name == "dedup_votes": self.only_one_vote_per_user_per_item() self.response.out.write("Votes Deduplicated") elif migration_name == "remove_brunch": self.remove_brunch() self.response.out.write("Brunch removed") elif migration_name == "five_star": self.votes_to_5_star() self.response.out.write("Stars set") elif migration_name == "reset-votes-json": self.wipe_votes_json() self.response.out.write("Json Wiped") elif migration_name == "rename-category": self.rename_category() self.response.out.write("Cat renamed") elif migration_name == "single-change-queue-places": self.single_change_queue_places() self.response.out.write("Queues merged") elif migration_name == "single-change-queue-votes": self.single_change_queue_votes() self.response.out.write("Queues merged") else: logging_ext.logging_ext.error("No Migration - %s"%migration_name) self.response.out.write("No Migration - %s"%migration_name)
def update_votes(): ''' Updates the Vote table with the json retrieved from Kimono. If a vote is not in the table it creates one. Returns the number of new votes and new orphan players added to the db ''' logger.info('Updating votes...') url = settings.KIMONO['votes_url'] votes = _get_results_collection1(url) # Keeping a list of players with votes but not present in the Player table # so that they could be added later logger.info(' - Updating database...') no_new_votes = 0 no_new_orphans = 0 for vote in votes: p_id = _id_from_url(vote['name']['href']) v_day = _day_from_url(vote['url']) # Checking if the vote already exists. If not, creates a new one, if it # exists it will get the current vote and update it try: v = Vote.objects.get(player__pk=p_id, day=v_day) except Vote.DoesNotExist: v = Vote() no_new_votes += 1 # Creating a orphan player if there is not a player for this vote try: p = Player.objects.get(pk=p_id) except Player.DoesNotExist: p = Player(pk=p_id) p.role = _fix_role(vote['role']) p.save() no_new_orphans += 1 v.player = p v.vote = _fix_zero(vote['vote']) v.gol = _fix_zero(vote['gol']) v.assist = _fix_zero(vote['assists']) v.penalties_scored_saved = _fix_zero(vote['penalties_scored_saved']) v.penalties_missed = _fix_zero(vote['penalties_missed']) v.own_gol = _fix_zero(vote['own_gol']) v.yellow_cards = _fix_zero(vote['yellow_cards']) v.red_cards = _fix_zero(vote['red_cards']) v.magicvote = _fix_zero(vote['own_gol']) v.day = v_day v.sub_in = _sub_in(vote['in']['class']) v.sub_out = _sub_out(vote['out']['class']) # Storing on the db v.save() return no_new_votes, no_new_orphans
def setup(): # clear tables first... Vote.delete().execute() Proposal.delete().execute() Superblock.delete().execute() GovernanceObject.delete().execute()
def setup(): # clear tables first Vote.delete().execute() Proposal.delete().execute() GovernanceObject.delete().execute()
def set_vote_time_to_now(self): votes = Vote.query() for v in votes: v.when = datetime.now() v.put()