def post(self, post_id, vote_default): post = post_exist(post_id) v = vote_exist(post_id, self.user.name) voteresult = self.request.get('voteresult') if not vote_default: vote_default = "votepost" if post: if self.user.name == post.created_by: error = "You cannot Like your own Post" self.render("errorpost.html", p=post, error=error) elif v.count() > 0: error = "You have already voted" self.render("errorpost.html", p=post, error=error) elif not voteresult: error = "You did not vote" + voteresult self.render(vote_default + ".html", p=post, error=error) else: v = Vote(parent=blog_key(), username_fk=self.user.name, post_id_fk=int(post_id), content=voteresult) v.put() self.redirect('/blog/%s' % post_id) else: self.redirect("/blog")
def make_vote(vote, mp, commons_division): if vote: vote_type = re.search(r'(?:#)(\w+?)(?:Vote)', vote['type']) vote_type = vote_type.group(1) else: vote_type = 'no_vote' vote = Vote() vote.set_vote_type(vote_type) vote.commons_division = commons_division vote.member_of_parliament = mp return vote
def save(): if request.method == 'POST': try: imgList = ['1d0', 'aqm', 'ckf', 'asm', '47c', '6mq'] img = random.choice(imgList) valueInput = request.form['valueInput'] vote = Vote(value=int(valueInput), image_id=img) res = RequestsApi.save_api(vote) #print(res) return redirect(url_for('index')) except: return "Not saved"
def instance(data): """ Given data from the database, return an appropriate model instance based on the `kind` field. """ if data.get('kind') == 'proposal': return Proposal(data) if data.get('kind') == 'vote': return Vote(data) return Post(data)
def click(selected_value, id): if selected_value: votes = Vote(vote=1, option_id=selected_value) db.session.add(votes) db.session.commit() flash(f"You voted successfully!") results = db.session.query(Options.choice, Vote.vote,)\ .filter_by(question_id=id).\ outerjoin(Vote, Options.id == Vote.option_id).all() return render_template('polls/results.html', results=results) return redirect(url_for('detail_view'))
def vote_comment(user=None): payload = request.get_json() comment_id = payload["comment_id"] existing_vote = Vote.query.filter(Vote.comment_id == comment_id, Vote.user_id == user['id']).first() if existing_vote: existing_vote.score = 1 if existing_vote.score == 0 else 0 else: db.session.add(Vote(comment_id=comment_id, user_id=user['id'], score=1)) db.session.commit() return "success"
def upvote(): import json form = request.form vote = Vote(form) if not vote.is_voted(): vote.save() blog_id = int(form.get('blog_id', 0)) Blog.upvote(blog_id) blog = Blog.query.get(blog_id) upvotes = blog.upvotes response = dict(status=1, vote_num=upvotes, msg='点赞成功') else: response = dict(status=0, msg='点赞失败') return json.dumps(response)
def createQuestionVote(accountId, questionId, value): vote = Vote() vote.AccountId = accountId vote.QuestionId = questionId vote.TimeStamp = datetime.datetime.now() if value is 1: vote.IsUpvote = True else: vote.IsUpvote = False db.session.add(vote) db.session.commit() return vote
def test_response(db_conn, posts_table): """ Expect a vote to require a response (None is okay). """ vote = Vote({ 'user_id': 'A', 'topic_id': 'B', 'replies_to_id': 'D', }) del vote['response'] vote, errors = vote.save() assert len(errors) == 0 vote['response'] = True vote, errors = vote.save() assert len(errors) == 0
def test_kind(db_conn, posts_table): """ Expect a vote to always have a kind of vote. """ vote = Vote({ 'user_id': 'A', 'topic_id': 'B', 'replies_to_id': 'D', 'response': True, }) del vote['kind'] vote, errors = vote.save() assert len(errors) == 1 vote['kind'] = 'vote' vote, errors = vote.save() assert len(errors) == 0
def test_response(db_conn, posts_table, units_table): """ Expect a vote to require a response. """ create_proposal(posts_table, units_table, db_conn) vote = Vote({ 'user_id': 'A', 'topic_id': 'B', 'replies_to_id': 'D', }) del vote['response'] vote, errors = vote.save(db_conn) assert len(errors) == 0 vote['response'] = True vote, errors = vote.save(db_conn) assert len(errors) == 0
def vote_on_a_poll(cls): poll_id = input("Enter the id of the poll you want to vote on: ") try: poll = Poll.select_by_id(int(poll_id)) except: print( "An error occurred. I can't find the poll id '{}' in the database. Please make sure you've entered a valid poll id." .format(poll_id)) cls.vote_on_a_poll() return options_list = Option.select_by_poll_id(poll_id) poll.print_poll_question() for option in options_list: option.print_option() users_vote = input("Enter an id of you answer: ") while users_vote not in [ str(option.option_id) for option in options_list ]: users_vote = input( "This is not a valid answer. Enter an id of you answer: ") users_name = input("Enter your name: ") while not users_name: users_name = input("Enter your name: ") users_timezone = input("Enter your timezone: ") while users_timezone not in pytz.all_timezones: users_timezone = input( "This is not a valid timezone. Try again. Enter your timezone: " ) users_timezone_obj = pytz.timezone(users_timezone) local_time_of_vote = users_timezone_obj.localize( datetime.datetime.now()) utc_timestamp = local_time_of_vote.astimezone(pytz.utc).timestamp() vote = Vote(users_vote, users_name, utc_timestamp) vote.save_to_db() input( f'\nThank you for participating in the poll, {users_name}! Press Enter to continue...' ) cls.select_from_menu()
def post(self, post_id): post = post_exist(post_id) v = vote_exist(post_id, self.user.name) if post: if self.user.name == post.created_by: error = "You cannot Like your own Post" self.render("errorpost.html", p=post, error=error) elif v: error = "You have already voted" self.render("errorpost.html", p=p, error=error) else: v = Vote(parent=blog_key(), user_fk=user, post_fk=post, content="Like") v.put() self.redirect('/blog/%s' % post_id) else: self.redirect("/blog")
def vote_post(parent_id, vote_type, parent_type): if check.logged_in(): if (parent_type == 0 or parent_type == 1) and (vote_type == 0 or vote_type == 1): ## parent type = 0 post ## parent type = 1 comment create_vote = False delete_vote = False try: if parent_type == 0: parent = Post(parent_id) user_vote = Vote.get_user_post_vote( session.get("user_id", ""), parent_id) elif parent_type == 1: parent = Comment(parent_id) user_vote = Vote.get_user_comment_vote( session.get("user_id", ""), parent_id) if not user_vote: #User did not vote this post before if (vote_type == 1 ): #If upvote increment the count, else decrement. parent.current_vote += 1 else: parent.current_vote -= 1 parent.save() create_vote = True else: #User voted this post before if user_vote[0].vote: #Previous vote was upvote if vote_type == 0: #User wants to change the vote to downwote parent.current_vote -= 2 user_vote[0].last_update_time = datetime.utcnow() user_vote[0].save() else: parent.current_vote -= 1 #User takes the vote back by clicking twice delete_vote = True #Vote will be delete else: #Previous vote was downvote if vote_type == 0: #Current vote is downvote parent.current_vote += 1 #Vote will be deleted since it was clicked twice delete_vote = True else: parent.current_vote += 2 #User wants to chane the vote to upvote user_vote[0].last_update_time = datetime.utcnow() user_vote[0].save() if delete_vote: user_vote[0].delete() else: user_vote[0].vote = bool(vote_type) user_vote[0].save() parent.save() #New vote gets created and sended as a JSON object if create_vote: vote = Vote() vote.date = datetime.utcnow() vote.is_comment = bool(parent_type) vote.vote = bool(vote_type) vote.vote_ip = request.remote_addr vote.last_update_time = datetime.utcnow() vote.user_id = session.get("user_id", "") vote.post_id = parent_id if parent_type == 0 else None vote.comment_id = parent_id if parent_type == 1 else None vote.save() return jsonify({ 'success': 'Successfuly voted!', 'final_vote': parent.current_vote }) except NotImplementedError as error: return jsonify({'error': str(error)}) return jsonify({'error': 'Invalid vote.'})
def _vote(self, vote_pool_id: int): """ Make the vote requests. :param int vote_pool_id: Vote pool ID. """ # Push an app context. app = create_app() app.app_context().push() # We need to create the model again because the same db session cannot # be used from two different threads. vote_pool = VotePool.query.filter(VotePool.id == vote_pool_id).first() # Add this pool to the list of running vote pools. running_vote_pool_ids.append(vote_pool.id) # Get the id of the accounts that already voted on the poll. screen_names = [] duplicated_vote_pools = VotePool.query.\ filter(VotePool.id != vote_pool.id).\ filter(VotePool.tweet_id == vote_pool.tweet_id).all() if duplicated_vote_pools: vote_pool_ids = [vp.id for vp in duplicated_vote_pools] votes = Vote.query.\ filter(Vote.vote_pool_id.in_(vote_pool_ids)).\ filter(Vote.hit == True).all() screen_names = [v.screen_name for v in votes] # Get the accounts that are the most likely to make a successful vote. # Custom order for status column. whens = { Account.STATUS_LOGGED_IN: 1, None: 2, Account.STATUS_UNCONFIRMED_ACCESS: 3, Account.STATUS_UNDETERMINED: 4, Account.STATUS_WRONG_CREDENTIALS: 5, Account.STATUS_SUSPENDED: 6 } status_order = case(value=Account.status, whens=whens) accounts = Account.query.\ filter(Account.screen_name.notin_(screen_names)).\ order_by( status_order, Account.status_updated_at.desc(), Account.id.desc() ).\ limit(vote_pool.max_tries).all() # Try while there are available accounts and the intended hits was not # reached. while accounts and self._hits < vote_pool.intended_hits: # Sleep for a random amount of time if the previos try was a hit. # Error could be undeclared. if 'error' in locals() and not locals()['error']: sleep(random() * 60) # Sleep for a maximum of one minute. account = accounts.pop(0) error = None # Try to vote. try: twitter_login = TwitterLogin(account) twitter_poll = \ TwitterPoll(vote_pool.tweet_id, twitter_login) twitter_poll.vote(vote_pool.option_index) except Exception as e: error = str(e) # Save the result. vote = Vote(vote_pool_id=vote_pool.id, create_datetime=datetime.utcnow(), screen_name=account.screen_name, email=account.email, password=account.password, phone_number=account.phone_number, hit=not error, error=error) db.session.add(vote) db.session.commit() if not error: self._hits += 1 # The vote pool has finished. Update its status. vote_pool.update_status(VotePool.STATUS_FINISHED) # Remove it from the list of running vote pools. running_vote_pool_ids.remove(vote_pool.id)