本文整理汇总了Python中models.Vote类的典型用法代码示例。如果您正苦于以下问题:Python Vote类的具体用法?Python Vote怎么用?Python Vote使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Vote类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: vote
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)
示例2: vote
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}})
示例3: api_poll_vote
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)
示例4: vote
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')
示例5: post_vote
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)
示例6: process_vote
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")
示例7: GET
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
],
})
示例8: vote
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!"
示例9: post
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')
示例10: update
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()
示例11: vote_post
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())
示例12: vote
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
示例13: voted
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)
示例14: polling_station_vote
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)
示例15: create_subject
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)