Esempio n. 1
0
 def test_was_published_recently_with_future_poll(self):
     """
     was_published_recently() should return False for polls whose
     pub_date is in the future
     """
     future_poll = Poll(pub_date=timezone.now() + datetime.timedelta(days=30))
     self.assertEqual(future_poll.was_published_recently(), False)
Esempio n. 2
0
    def setUp(self):
        basedir = os.path.abspath(os.path.dirname(__file__))
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + os.path.join(
            basedir, "test.db")
        self.app = app.test_client()  # create virtual test env
        db.create_all()
        s1 = User(username="******", email="*****@*****.**")
        s1.set_password("Hello")
        s2 = User(username="******", email="*****@*****.**")
        s2.set_password("World")
        poll1 = Poll(title="My First Poll",
                     user_id=1,
                     expiry_date=datetime.now())
        poll2 = Poll(title="Hello World",
                     user_id=2,
                     expiry_date=datetime.now() + timedelta(days=30))
        resp1 = Responses(value=datetime.now(), poll_id=1)
        vote1 = Votes(response_id=1, user_id=1, poll_id=1)
        vote2 = Votes(response_id=1, user_id=2, poll_id=1)

        db.session.add(s1)
        db.session.add(s2)
        db.session.add(poll1)
        db.session.add(resp1)
        db.session.add(vote1)
        db.session.add(vote2)
        db.session.add(poll2)
        db.session.commit()
Esempio n. 3
0
def create():
    form = CreatePollForm()
    if form.validate_on_submit():
        validationPoll=Poll.query.filter_by(title=form.title.data).first()
        if validationPoll!= None:
            flash(Markup('<script>Notify("There is already a poll created with the same title.", null, null, "danger")</script>'))
            return redirect(url_for('main.create'))

        else:
            poll=Poll(title=form.title.data, description=form.description.data,  minResponses=0, orderCandidatesBy=None, isOpenPoll=form.isOpen.data, openAt=None, closeAt=None, User=current_user)
            candidates=form.options
            nullCount=len(form.options)

            for item in candidates:
                if item.data != None and item.data != "":
                    poll.addCandidate(item.data, None)
                    nullCount-=1
            if nullCount > (len(form.options)-2):
                flash(Markup('<script>Notify("There is not enough choices to make this poll.", null, null, "danger")</script>'))
                return redirect(url_for('main.create'))
            else:
                if createPoll(poll)==True:
                    flash(Markup('<script>Notify("Poll has been created successfully!", null, null, "success")</script>'))
                    return redirect(url_for('main.current')+'/'+ str(poll.pollId))

                else:
                    flash(Markup('<script>Notify("Something is wrong!", null, null, "danger")</script>'))
                    return redirect(url_for('main.create'))
    return render_template('create.html', title='Create a Poll', form=form)
Esempio n. 4
0
def create_new_poll():
  errors=["An error occurred while creating a poll."]
  form = PollForm()
  form['csrf_token'].data = request.cookies['csrf_token']

  if form.validate_on_submit():
    new_poll = Poll(title=form.data['title'], question_text=form.data["question_text"], user_id=current_user.get_id())
    db.session.add(new_poll)
    db.session.commit()
    return { new_poll.get_id(): new_poll.to_dict() }

  return { "errors": errors }
Esempio n. 5
0
def archiveResponse(Poll, userId):
    if Poll != None:
        noResponses = Poll.howManyResponses() * Poll.howManyCandidates()
        for index in range(noResponses):
            if Poll.Response[index].userId == userId:
                Poll.Response[index].isActive = 0
                try:
                    db.session.add(Poll.Response[index])
                    db.session.commit()
                except:
                    return False
        return True
    else:
        return False
Esempio n. 6
0
    def __init__(self, mapping, fvars):

        # Parent constructor
        web.application.__init__(self, mapping, fvars) #@UndefinedVariable

        # The views are bound once for all to the configuration
        config.views = web.template.render("app/views/", globals={
            "all_seasons": lambda: Season.all(),
            "all_polls": lambda: Poll.all(),
            "webparts": webparts,
            "formatting": formatting,
            "dates": dates,
            "zip": zip,
            "getattr": getattr,
            "hasattr": hasattr,
            "class_name": lambda x: x.__class__.__name__,
            "namedtuple": collections.namedtuple,
            "config": config,
            "result_statuses": Result.STATUSES,
            "Events": Events
        })

        # The ORM is bound once since it dynamically loads the engine from the configuration
        config.orm = meta.init_orm(lambda : config.engine)

        # Binds the hooking mechanism & the SQL Alchemy processor
        self.add_processor(web.loadhook(http.init_hooks))
        self.add_processor(web.unloadhook(http.execute_hooks))        
        self.add_processor(http.sqlalchemy_processor)

        # Binds the webparts initialization mechanism
        self.add_processor(web.loadhook(webparts.init_webparts))
Esempio n. 7
0
def import_poll(json_file_path, name):
    """
    Import poll contained in file at JSON_FILE_PATH under the name NAME
    (if present) or the file name.
    """
    from app.models import Poll

    dir, file = os.path.split(json_file_path)
    file_name, ext_name = os.path.splitext(file)
    if ext_name != '.json':
        raise TypeError('Expected json file, got {}'.format(ext_name))

    name = name or file_name
    try:
        p = Poll.import_from_local(name, json_file_path)
    except IntegrityError as e:
        if 'UNIQUE' in e.args[0]:
            click.echo('Error : poll "{}" already exists !'.format(
                e.params[0]))
            return

        raise e
    except InvalidRequestError as e:
        if 'Table' in e.args[0]:
            click.echo('Error : poll "{}" already exists !'.format(name))
            return

        raise e

    click.echo(
        "Successfully imported poll '{}', available at url : polls/{}".format(
            p.name, p.slug))
Esempio n. 8
0
    def test_poll_init(self):
        
        
        title='test_poll_init - where is your favorite fishing spot?'
        description='test_poll_init - survey to find out the most favorite fishing spot in Perth'
        user=User.query.filter_by(userId=1).first()
 
        minResponses=5 #if not specified, the default value is -1 which will be ignored
        orderCandidatesBy=None #if not specified, the default value is alphabel acending 'Acs'
        isOpenPoll=None #if not specified, the default value is False
        openAt=None #if not specified, the default value is utcnow()
        closeAt=None  # if not specified, the default value is today + 7 days
        poll=Poll(title, description, minResponses, orderCandidatesBy, isOpenPoll, openAt, closeAt, user)
        
        assert_that(len(poll.Candidate)).is_equal_to(0)
        assert_that(len(poll.Response)).is_equal_to(0)


        assert_that(type(poll.createdAt)).is_equal_to(type(datetime.utcnow())) ##needs review
        assert_that(poll.title).is_equal_to(title)
        assert_that(poll.description).is_equal_to(description)
        assert_that(poll.createdByUserId).is_equal_to(user.userId)
        assert_that(poll.minResponses).is_equal_to(minResponses)
        assert_that(poll.orderCandidatesBy).is_equal_to('Acs')
        assert_that(poll.isOpenPoll).is_equal_to(False)



        assert_that(poll.openAt.strftime("%x")).is_equal_to(datetime.utcnow().strftime("%x"))
        assert_that(poll.closeAt.strftime("%x")).is_equal_to((datetime.utcnow()+timedelta(days=7)).strftime("%x"))   #need to check +7days
        assert_that(poll.lastModifiedAt).is_equal_to(None)
        assert_that(poll.completedAt).is_equal_to(None)
        
        assert_that(poll.isActive).is_equal_to(1)
Esempio n. 9
0
def create_vote():
    users = [(user.id, user.login) for user in User.query.all()]
    form = PollForm()
    form.access_participation.choices = users
    form.access_results.choices = users
    if form.validate_on_submit():
        new_poll = Poll(title=form.title.data, kind='vote', repeat_type=form.repeat_type.data,
                        creator=current_user)
        for participant_id in form.access_participation:
            new_poll.access_participation.append(User.query.get(int(participant_id.data)))

        for user_id in form.access_results:
            new_poll.access_results.append(User.query.get(int(user_id.data)))

        question = form.vote_questions[0]
        if question.question.data:
            new_question = Question(type='variants', question=question.question.data,
                                    multiple_answers=question.multiple_answers.data)
            for option in question.options:
                if option.data:
                    possible_answer = PossibleAnswer(option=option.data, question=new_question)
                    new_question.possible_answers.append(possible_answer)
            new_poll.questions.append(new_question)
            db.session.add(new_poll)
            db.session.commit()
            return redirect(url_for('index'))
    if len(form.questions) == 0:
        form.vote_questions.append_entry()
    return render_template('createVote.html', form=form)
Esempio n. 10
0
def add_poll():
    if current_user.is_admin:
        form = PollForm()

        if form.validate_on_submit():
            poll = Poll(name=form.name.data,
                        description=form.description.data,
                        creator_id=current_user.id)

            db.session.add(poll)
            db.session.flush()  # lets you access the generated poll.id

            for r in form.recipes:
                recipe = Recipe(name=r.data['name'],
                                description=r.data['description'],
                                contributor_id=current_user.id,
                                poll_id=poll.id)

                db.session.add(recipe)

            db.session.commit()  # commits all the changes in the database
            flash('The poll is added', 'success')
            return redirect(url_for('add_poll'))

        return render_template('poll_form.html',
                               title='Create Poll',
                               description='Fill in the details of the poll',
                               legend='Create a Poll',
                               form=form)
    else:
        abort(403)
Esempio n. 11
0
    def __init__(self):

        # Grid initialization
        super(EditPollsGrid, self).__init__(
            Poll, Poll.all(joined_attrs=["choices"]))  #@UndefinedVariable

        # Creation of customized date fields to edit the poll dates
        self.append(
            create_date_field("formatted_start_dt",
                              "start_dt",
                              DT_FORMAT,
                              today_by_default=True))
        self.append(
            create_date_field("formatted_end_dt",
                              "end_dt",
                              DT_FORMAT,
                              today_by_default=False))
        self.append(
            Field(name="formatted_possible_dates",
                  value=lambda model: "[%s]" % ",".join([
                      formatting.format_date(dt, DT_FORMAT)
                      for dt in model.possible_dates
                  ])))

        # Grid configuration
        inc = [
            TITLE(self.title),
            FORMATTED_START_DT(self.formatted_start_dt),
            FORMATTED_END_DT(self.formatted_end_dt),
            FORMATTED_POSSIBLE_DATES_READONLY(self.formatted_possible_dates)
        ]
        self.configure(include=inc)
Esempio n. 12
0
def create_poll():
    form = CreatePollForm()
    if form.validate_on_submit():
        new_poll = Poll(title=form.title.data, public=form.public.data, description=form.description.data)
        current_user.polls.append(new_poll)

        for question in form.questionList.data:
            if question['questionType'] == "sliderField":

                new_question = Question(question_title=question['questionTitle'], type="sliderField",
                                        lower_label=question['answerList'][0]['answer'],
                                        upper_label=question['answerList'][1]['answer'])
                new_poll.questions.append(new_question)
                for num in range(1, 11):
                    new_answer = Answer(answer=num)
                    new_question.answers.append(new_answer)
            else:
                new_question = Question(question_title=question['questionTitle'], type=question['questionType'])
                new_poll.questions.append(new_question)

                if question['questionType'] == "textField":
                    new_answer = Answer(answer="text")
                    new_question.answers.append(new_answer)

                for answer in question['answerList']:
                    new_answer = Answer(answer=answer['answer'])
                    new_question.answers.append(new_answer)

        db.session.commit()
        #poll_created_email(current_user, new_poll)
        return redirect(url_for('poll_preview', poll_id=new_poll.id))

    return render_template('create_poll.html', form=form)
Esempio n. 13
0
def createEbook(app, blog, headers):
    with app.app_context():
        url = blogs[blog]['url']

        toSend = req(url=url, headers=headers)

        xml = urlopen(toSend).read()
        rss_feed = BeautifulSoup(xml, 'xml')

        # Find last build date. If none, set to default date 11 Mar 2019
        new_update = rss_feed.find('lastBuildDate')
        if new_update is not None:
            new_update = datetime.strptime(
                rss_feed.find('lastBuildDate').text.strip(),
                "%a, %d %b %Y %H:%M:%S +0000")
        else:
            print("rss feed for {} has no default time".format(blog))
            new_update = datetime.now()

        # Retrieve last date polled from database
        # if not in database, create new poll entry
        last_updated = Poll.query.filter(Poll.name == blog).first()

        if last_updated.time == new_update:
            print("skipping {}".format(blog))
            return

        if last_updated is None:
            new_time = datetime.now()
            last_updated = Poll(name=blog, time=new_time)
            db.session.add(last_updated)
        else:
            print("setting new time for {}. Time is: {}".format(
                blog, new_update))
            last_updated.time = new_update

        db.session.commit()

        print("creating {}".format(blog))

        parseWorker(blog)

        book_creator.createEBook(blog)

        sendByBlog(blog)
Esempio n. 14
0
def create_poll():
    if(request.method == "GET"):
        return(render_template("create-poll.html",title = "Create a new poll"))
    if(request.get_json()):
        data = request.get_json()
        if(not data):
            response_dict = {"message" : "Validation error, please make sure javascript is enabled for this site"}
            resp = make_response(response_dict)
            resp.headers["status"] = 400
            return(resp)
        try:
            title = data["title"]
            description = data["description"]
            options = data["options"]
            expiry_date = data["expiry_date"]
            options_limit = data["options_limit"]
        except KeyError as e:
            return(jsonify({"url" : False}), 400)
        if(not options_limit):
            options_limit = -1
        if(not expiry_date):
            return(jsonify({"url" : False}), 400)
        
        expiry_date = datetime.fromtimestamp(expiry_date / 1000.0) 
        for i in range(len(options)):
            if(not options[i]):
                del options[i]
            try:
                options[i] = datetime.fromtimestamp(options[i] / 1000.0)
            except TypeError as e:
                return(jsonify({"url" : False}), 400)
        if(not title):
            return(jsonify({"url" : False}), 400)
        if(not options):
            return(jsonify({"url" : False}), 400)
        poll = Poll(title = title, description = description, expiry_date = expiry_date, option_limit = int(options_limit), user_id = current_user.id)
        db.session.add(poll)
        db.session.commit()
        poll.check_display_picture()
        for i in range(len(options)):
            resp = Responses(value = options[i], poll_id = poll.id) 
            db.session.add(resp)
        db.session.commit()
        response_dict = {"url": poll.id}
    return(jsonify(response_dict))
Esempio n. 15
0
def new_poll():
    form = MakePollForm()
    if request.method == "POST" and form.validate_on_submit():
        poll = Poll(author=current_user, name=form.name.data,expiration=form.expiration.data)
        db.session.add(poll)
        db.session.commit()
        flash('Poll added, now add questions')
        return redirect(url_for('add_questions', poll_id=poll.id))
    return render_template('new_poll.html', title='create', form=form)
Esempio n. 16
0
 def test_all(self):
     
     all_polls = Poll.all()
     self.assertEqual(len(all_polls), 3)
     
     # Checks the order by clause
     self.assertEqual(all_polls[0].start_dt, datetime.date(2011, 5, 28))
     self.assertEqual(all_polls[1].start_dt, datetime.date(2012, 4, 5))
     self.assertEqual(all_polls[2].start_dt, datetime.date(2020, 10, 1))
Esempio n. 17
0
 def GET(self):
     
     open_polls = filter(lambda poll: not poll.expired, Poll.all())
     
     return config.views.layout(
         config.views.index(
             pending_tournaments(),
             open_polls,
             News.all()
         )
     )
Esempio n. 18
0
def seed(request):
    """Seeds the database with sample polls."""
    samples_path = path.join(path.dirname(__file__), 'samples.json')
    with open(samples_path, 'r') as samples_file:
        samples_polls = json.load(samples_file)

    for sample_poll in samples_polls:
        poll = Poll()
        poll.text = sample_poll['text']
        poll.pub_date = timezone.now()
        poll.save()

        for sample_choice in sample_poll['choices']:
            choice = Choice()
            choice.poll = poll
            choice.text = sample_choice
            choice.votes = 0
            choice.save()

    return HttpResponseRedirect(reverse('app:home'))
Esempio n. 19
0
def add_poll():
    """ Function that allows admin to create a new poll """
    error = None
    form = PollForm(csrf_enabled=False)
    if form.validate_on_submit():
        new_poll = Poll(form.question.data)
        db.session.add(new_poll)
        db.session.commit()
        flash('New entry was successfully posted. Thanks.')
    else:
        flash_errors(form)
    return redirect(url_for('admin_main'))
Esempio n. 20
0
    def POST(self):

        # Reads the HTTP request parameters
        http_input = web.input(poll_id=None, poll_user_choices=[])
        poll_id = http_input.poll_id
        poll_user_choices = http_input.poll_user_choices

        # Loads the poll
        if poll_id is None:
            raise web.notfound()

        poll = Poll.get(int(poll_id),
                        joined_attrs=["choices", "votes_by_user"])

        if poll is None:
            raise web.notfound()

        # Passes the user's choices to the model
        try:

            # Parses the choice numbers & makes sure they're valid
            poll_user_choices = map(int, poll_user_choices)
            if any(i not in range(len(poll.choices))
                   for i in poll_user_choices):
                raise ValueError(
                    u"Un des entiers passes a la methode /poll/vote n'est pas compris dans l'intervalle %s"
                    % range(len(poll.choices)))

            # Determines if it's the first vote ever in the poll
            someone_already_voted = poll.has_votes

            # Determines if it's the first vote for the user
            user_already_voted = config.session_manager.user in poll.choices_by_user

            # Actual vote action for the user
            poll_vote = poll.vote(config.session_manager.user,
                                  [poll.choices[i] for i in poll_user_choices])

            # Registers an email notification
            http.register_hook(lambda: notify_via_email(
                poll_vote, Events.MODIFIED
                if user_already_voted else Events.NEW))

            return dict(data=config.views.poll_votes(
                poll,
                highlight_user=config.session_manager.user
                if someone_already_voted else None),
                        partial=someone_already_voted)

        except ValueError as exception:
            raise http.Forbidden(exception)
Esempio n. 21
0
def newPoll():
    title = 'Crear nueva votación'
    poll = Poll(start_date=datetime.datetime.utcnow())
    form = NewPollForm(obj=poll,
                       start_time=datetime.time(18, 15),
                       end_time=datetime.time(18, 30))
    if (form.validate_on_submit()):
        form.populate_obj(poll)
        poll.start_date = datetime.datetime.combine(form.start_date.data,
                                                    form.start_time.data)
        poll.end_date = datetime.datetime.combine(form.end_date.data,
                                                  form.end_time.data)
        poll.id_creator = current_user.id
        options = list(form.Opciones.data.split("; "))
        try:
            for option in options:
                if ("$user: "******"user_id: x" para clasificar
                    analized_option = option.split(" ", 1)[1]
                    user = User.query.filter_by(
                        Usuario=analized_option).first_or_404()
                    if (user is not None):
                        option = "user_id: " + str(user.id)  #
                elif ("$date: " in option):
                    #Y aqui un elemento "date" Aunque, quizas habria que hacer el template_html mas dinamico
                    analized_option = option.split(" ", 1)[1]
                opcion = PollOption(option_name=option)
                poll.options.append(opcion)
            db.session.add(poll)
            db.session.commit()
            #print(options, flush=True)
            return render_template('ShowNewPoll.html', options=options)
        except:
            flash(
                'Error!!! Ha sucedido un error, revisa que todos los datos han sido introducidos correctamente'
            )
            return render_template('Newpoll.html', title=title, form=form)
    return render_template('Newpoll.html', title=title, form=form)
    def setUp(self):
        basedir = os.path.abspath(os.path.dirname(__file__))
        app.config['SQLALCHEMY_DATABASE_URI'] =\
            'sqlite:///' + os.path.join(basedir, 'test.db')
        app.config['TESTING'] = True
        app.config['WTF_CSRF_ENABLED'] = False
        self.app = app.test_client()
        db.create_all()

        u1 = User(username='******', email='*****@*****.**')
        u1.set_password('password')

        admin1 = User(username='******', email='*****@*****.**', is_admin=True)
        admin1.set_password('admin')

        db.session.add(u1)
        db.session.commit()

        poll1 = Poll(name='poll1', description='pdesc', creator_id=u1.id)
        poll2 = Poll(name='poll2', description='p2desc', creator_id=u1.id)

        db.session.add(poll1)
        db.session.add(poll2)
        db.session.commit()

        recipe1 = Recipe(name='recipe1',
                         description='rdesc',
                         contributor_id=u1.id,
                         poll_id=poll1.id)

        db.session.add(recipe1)
        db.session.commit()

        vote1 = Vote(poll_id=poll1.id, user_id=u1.id, recipe_id=recipe1.id)

        db.session.add(admin1)
        db.session.add(vote1)
        db.session.commit()
Esempio n. 23
0
def seed_polls():

    count = 100
    result = []
    while count > 0:
        result.append(
            Poll(title=fake.text(max_nb_chars=50),
                 question_text=fake.text(max_nb_chars=100),
                 user_id=randint(1, 200)))
        count -= 1

    for poll in result:
        db.session.add(poll)
        db.session.commit()
Esempio n. 24
0
def reset():
    if (current_user.id != 1):
        return
    for blog in BlogName:
        last_updated = Poll.query.filter(Poll.name == blog).first()
        if last_updated is None:
            poll = Poll(name=blog, time=DEFAULT_TIME)
            db.session.add(poll)
        else:
            last_updated.time = DEFAULT_TIME
        db.session.commit()

    r = Response(str("times reset"), status=200)
    return r
Esempio n. 25
0
    def test_poll_howManyResponses(self):

        poll=Poll.query.filter_by(pollId=1).first()
        
        assert_that(poll.howManyResponses()).is_equal_to(0)

        response1=Poll.Response()
        response1.userId=userId
        response1.pollId=poll.pollId
        response1.candidateId=1
        response1.response=1
        response1.createdAt=datetime.utcnow()
        response1.isActive=True
        poll.Response.append(response1)
Esempio n. 26
0
def createPoll(Poll):
    if Poll == None:
        print('Poll object is empty')
        return False
    else:
        if Poll.validate():
            try:
                db.session.add(Poll)
                db.session.commit()
                for index in range(Poll.howManyCandidates()):
                    Poll.Candidate[index].pollId = Poll.get_id()
                    try:
                        db.session.add(Poll.Candidate[index])
                        db.session.commit()
                    except:
                        return 'create candidate exception raised: ' + str(
                            sys.exc_info()[0])
                return True
            except:
                return 'createPoll exception raised: ' + str(sys.exc_info()[0])
        else:
            print('Mandatory data for a poll missing')
            return False
Esempio n. 27
0
    def GET(self, poll_id):

        # Loads the poll
        poll = Poll.get(int(poll_id),
                        joined_attrs=["choices", "votes_by_user", "comments"])

        if poll is None:
            raise web.notfound()

        return config.views.layout(
            config.views.poll(
                poll, config.views.poll_header(poll),
                config.views.poll_vote_unit(poll),
                config.views.poll_votes(poll),
                config.views.comments(poll, config.views.comment)))
Esempio n. 28
0
def create_poll(emojis: list, session: Session = None) -> Poll:
    """
    Создать опрос

    :param emojis: Массив эмодзи для вариантов ответа
    :param session:
    :return: Созданный опрос
    """
    poll = Poll()
    session.add(poll)
    for emoji in emojis:
        option = PollOption()
        option.poll = poll
        option.text = emoji
        session.add(option)
    return poll
Esempio n. 29
0
 def GET(self, poll_id):
     
     # Loads the poll
     poll = Poll.get(int(poll_id), joined_attrs=["choices", "votes_by_user", "comments"])
     
     if poll is None:
         raise web.notfound()
     
     return config.views.layout(
                config.views.poll(
                     poll,
                     config.views.poll_header(poll),
                     config.views.poll_vote_unit(poll),
                     config.views.poll_votes(poll),
                     config.views.comments(poll, config.views.comment)
                 )
             )
Esempio n. 30
0
def seed(request):
    """Seeds the database with sample polls."""
    samples_path = path.join(path.dirname(__file__), 'samples.json')
    with open(samples_path, 'r') as samples_file:
        samples_polls = json.load(samples_file)

    for sample_poll in samples_polls:
        poll = Poll()
        poll.Geplanter_Status()
        poll.Status()
        poll.Kurzbeschreibung = sample_poll['Kurzbeschreibung']
        poll.text = sample_poll['text']
        poll.pub_date = true
        poll.save()

        for sample_choice in sample_poll['choices']:
            choice = Choice()
            choice.poll = poll
            choice.text = sample_choice
            choice.Status = 0
            choice.save()

    return HttpResponseRedirect(reverse('app:home'))
Esempio n. 31
0
    def POST(self):
        
        # Reads the HTTP request parameters
        http_input = web.input(poll_id=None, poll_user_choices=[])
        poll_id = http_input.poll_id
        poll_user_choices = http_input.poll_user_choices

        # Loads the poll
        if poll_id is None:
            raise web.notfound() 

        poll = Poll.get(int(poll_id), joined_attrs=["choices", "votes_by_user"])

        if poll is None:
            raise web.notfound()
        
        # Passes the user's choices to the model
        try:
            
            # Parses the choice numbers & makes sure they're valid
            poll_user_choices = map(int, poll_user_choices)
            if any(i not in range(len(poll.choices)) for i in poll_user_choices):
                raise ValueError(u"Un des entiers passes a la methode /poll/vote n'est pas compris dans l'intervalle %s" % range(len(poll.choices)))
            
            # Determines if it's the first vote ever in the poll
            someone_already_voted = poll.has_votes
            
            # Determines if it's the first vote for the user
            user_already_voted = config.session_manager.user in poll.choices_by_user
            
            # Actual vote action for the user
            poll_vote = poll.vote(config.session_manager.user, [poll.choices[i] for i in poll_user_choices])

            # Registers an email notification
            http.register_hook(lambda: notify_via_email(poll_vote, Events.MODIFIED if user_already_voted else Events.NEW))

            return dict(
                data=config.views.poll_votes(poll, highlight_user=config.session_manager.user if someone_already_voted else None),
                partial=someone_already_voted
            )
            
        except ValueError as exception:
            raise http.Forbidden(exception)
Esempio n. 32
0
    def test_poll_isClosed(self):
        title='test_poll_isClosed -  where is your favorite fishing spot?'
        description='survey to find out the most favorite fishing spot in Perth'
        user=User.query.filter_by(userId=1).first()
 
        minResponses=5 #if not specified, the default value is -1 which will be ignored
        orderCandidatesBy=None #if not specified, the default value is alphabel acending 'Acs'
        isOpenPoll=None #if not specified, the default value is False
        openAt=None #if not specified, the default value is utcnow()
        closeAt=None  # if not specified, the default value is today + 7 days
        poll=Poll(title, description, minResponses, orderCandidatesBy, isOpenPoll, openAt, closeAt, user)
        
        assert_that(poll.isClosed()).is_equal_to(False)
        
        poll.close()

        assert_that(poll.isClosed()).is_equal_to(True)
Esempio n. 33
0
    def __init__(self):
        
        # Grid initialization
        super(EditPollsGrid, self).__init__(Poll, Poll.all(joined_attrs=["choices"])) #@UndefinedVariable

        # Creation of customized date fields to edit the poll dates
        self.append(create_date_field("formatted_start_dt", "start_dt", DT_FORMAT, today_by_default=True))
        self.append(create_date_field("formatted_end_dt", "end_dt", DT_FORMAT, today_by_default=False))
        self.append(
            Field(
                name="formatted_possible_dates",
                value=lambda model: "[%s]" % ",".join([formatting.format_date(dt, DT_FORMAT) for dt in model.possible_dates])
            )
        )
        
        # Grid configuration
        inc = [
            TITLE(self.title),
            FORMATTED_START_DT(self.formatted_start_dt),
            FORMATTED_END_DT(self.formatted_end_dt),
            FORMATTED_POSSIBLE_DATES_READONLY(self.formatted_possible_dates)
        ]
        self.configure(include=inc)
Esempio n. 34
0
    def POST(self):

        # Reads the HTTP request parameters
        http_input = web.input()
        poll_id = http_input.poll_id
        comment = http_input.comment

        # Loads the poll
        if poll_id is None:
            raise web.notfound()

        poll = Poll.get(int(poll_id), joined_attrs=["comments"])

        if poll is None:
            raise web.notfound()

        # Appends the comment
        poll_comment = poll.add_comment(config.session_manager.user, comment)

        # Registers an email notification
        http.register_hook(lambda: notify_via_email(poll_comment, Events.NEW))

        # Returns the dictionary
        return config.views.comment(poll_comment)
Esempio n. 35
0
    def POST(self):
        
        # Reads the HTTP request parameters
        http_input = web.input()
        poll_id = http_input.poll_id
        comment = http_input.comment

        # Loads the poll
        if poll_id is None:
            raise web.notfound() 

        poll = Poll.get(int(poll_id), joined_attrs=["comments"])

        if poll is None:
            raise web.notfound()
        
        # Appends the comment
        poll_comment = poll.add_comment(config.session_manager.user, comment)
        
        # Registers an email notification
        http.register_hook(lambda: notify_via_email(poll_comment, Events.NEW))

        # Returns the dictionary
        return config.views.comment(poll_comment)
Esempio n. 36
0
def seed(request):
    """Seeds the database with sample polls."""
    samples_path = path.join(path.dirname(__file__), 'samples.json')
    with open(samples_path, 'r') as samples_file:
        samples_polls = json.load(samples_file)

    for sample_poll in samples_polls:
        poll = Poll()
        poll.text = sample_poll['text']
        poll.pub_date = timezone.now()
        poll.save()

        for sample_choice in sample_poll['choices']:
            choice = Choice()
            choice.poll = poll
            choice.text = sample_choice
            choice.votes = 0
            choice.save()

    return HttpResponseRedirect(reverse('app:home'))
Esempio n. 37
0
from app import db
from app.models import Poll, Choice, Admin
from datetime import date

db.drop_all()
db.create_all()

# playing around with multiple ways to create db obects

p = Poll('Will you go with me?')
y = Choice('yes')
y.poll = p
n = Choice('no')
n.poll = p
db.session.add_all([p,y,n])

sure = Choice('sure')
nope = Choice('nope')
new = Poll('Can I call you sometime?')
sure.poll = new
nope.poll = new
db.session.add_all([new, sure, nope])
#db.session.commit()

q = Poll('You got a phone number?')
a = Choice('NO!')
b = Choice('YESS!.')
a.poll = q
b.poll = q
db.session.add_all([a, b, q])