本文整理汇总了Python中models.Vote类的典型用法代码示例。如果您正苦于以下问题:Python Vote类的具体用法?Python Vote怎么用?Python Vote使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Vote类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:stealthycoin,项目名称:toilet_mapper,代码行数:26,代码来源:middletier.py
示例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}})
开发者ID:spncrlkt,项目名称:emoji-be,代码行数:34,代码来源:app.py
示例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)
开发者ID:krdeepak,项目名称:djmysite,代码行数:30,代码来源:views.py
示例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')
开发者ID:kleinab,项目名称:caesar-web,代码行数:25,代码来源:views.py
示例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)
开发者ID:warownia1,项目名称:TheResistance,代码行数:28,代码来源:views.py
示例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")
开发者ID:PeggyZheng,项目名称:Opinionated,代码行数:31,代码来源:server.py
示例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
],
})
开发者ID:dwt,项目名称:congo,代码行数:30,代码来源:game.py
示例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!"
开发者ID:amyrlam,项目名称:earthmd,代码行数:33,代码来源:views.py
示例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')
开发者ID:grillermo,项目名称:Noticias-HAcker,代码行数:26,代码来源:PostHandler.py
示例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()
开发者ID:dougo,项目名称:chugchanga-poll,代码行数:35,代码来源:main.py
示例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())
开发者ID:nephthys,项目名称:insidetags,代码行数:29,代码来源:views.py
示例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
开发者ID:jcrocholl,项目名称:minderbot,代码行数:29,代码来源:views.py
示例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)
开发者ID:markbreneman,项目名称:SmartMoVote,代码行数:32,代码来源:app.py
示例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)
开发者ID:svobodni,项目名称:ballot_box,代码行数:58,代码来源:views.py
示例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)
开发者ID:CMGS,项目名称:poll,代码行数:11,代码来源:query.py
示例16: vote
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"])
开发者ID:NSkelsey,项目名称:cvf,代码行数:12,代码来源:views.py
示例17: prefetch_posts_list
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 =", user).filter("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)
开发者ID:DFectuoso,项目名称:Noticias-HAcker,代码行数:52,代码来源:prefetch.py
示例18: test_votes
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)
开发者ID:bendominguez011,项目名称:community-project,代码行数:13,代码来源:tests.py
示例19: handle_call_request
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')
开发者ID:BantouTelecom,项目名称:ClueCon,代码行数:51,代码来源:views.py
示例20: post
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'})
开发者ID:miholeus,项目名称:lovepython,代码行数:29,代码来源:views.py
注:本文中的models.Vote类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论