Exemple #1
0
def api_polls():

    if request.method == 'POST':

        #Get poll and save in the database
        poll = request.get_json()

        for key, value in poll.items():
            if not value:
                return jsonify(
                    {'message': 'value for {} is empty'.format(key)})

        title = poll['title']
        options_query = lambda option: Options.query.filter(
            Options.name.like(option))
        options = [
            Polls(option=Options(
                name=option)) if options_query(option).count() == 0 else Polls(
                    option=options_query(option).first())
            for option in poll['options']
        ]

        new_topic = Topics(title=title, options=options)

        db.session.add(new_topic)
        db.session.commit()

        return jsonify({'message': 'Poll was successfully created!'})

    else:
        #Query the database and return all polls as JSON objects
        polls = Topics.query.join(Polls).order_by(Topics.id.desc()).all()
        all_polls = {'Polls': [poll.to_json() for poll in polls]}

        return jsonify(all_polls)
Exemple #2
0
def api_polls():
    if request.method == 'POST':
        # get the poll and save it in the database
        poll = request.get_json()

        # simple validation to check if all values are properly secret
        for key, value in poll.items():
            if not value:
                return jsonify({'error': 'value for {} is empty'.format(key)})

        title = poll['title']
        options_query = lambda option: \
            Options.query.filter(Options.name.like(option))

        options = [
            Polls(option=Options(
                name=option)) if options_query(option).count() == 0 else Polls(
                    option=options_query(option).first())
            for option in poll['options']
        ]

        new_topic = Topics(title=title, options=options)

        db.session.add(new_topic)
        db.session.commit()

        return jsonify({'message': 'Poll was created succesfully'})

    else:
        # it's a GET request, return dict representations of the API
        polls = Topics.query.join(Polls).all()
        all_polls = {'Polls': [poll.to_json() for poll in polls]}

        return jsonify(all_polls)
Exemple #3
0
def add():
    if request.method=="POST":
        nama_pemilih = request.form.get("name",None)
        pilihan = request.form.get("pilihan",None)

        polls = Polls(nama_pemilih,pilihan)
        polls.created_time=datetime.datetime.now()
        db.session.add(polls)
        db.session.commit()
        return redirect('/polls')
    return render_template("add_user.html",**locals())
Exemple #4
0
def addpoll():
    if request.method == "POST":
        name = request.form.get("name", None)
        candidate = request.form.get("candidate", None)
        # create new record in database
        polls = Polls(name,candidate)
        polls.createdtime = datetime.datetime.now()
        database.session.add(polls)
        database.session.commit()
        return redirect("/polls")

    return render_template("pollsadd.html", **locals())
Exemple #5
0
def api_polls():
    if request.method == 'POST':
        # get the poll and save it in the database
        poll = request.get_json()

        # simple validation to check if all values are properly set
        for key, value in poll.items():
            if not value:
                return jsonify(
                    {'message': 'value for {} is empty'.format(key)})

        title = poll['title']

        # return option that matches a given name
        def options_query(option):
            return Options.query.filter(Options.name.like(option))

        options = [
            Polls(option=Options(
                name=option)) if options_query(option).count() == 0 else Polls(
                    option=options_query(option).first())
            for option in poll['options']
        ]

        eta = datetime.utcfromtimestamp(poll['close_date'])
        new_topic = Topics(title=title, options=options, close_date=eta)

        db.session.add(new_topic)
        db.session.commit()

        # run the task
        from tasks import close_poll

        close_poll.apply_async((new_topic.id, env['SQLALCHEMY_DATABASE_URI']),
                               eta=eta)

        return jsonify({'message': 'Poll was created succesfully'})

    else:
        # it's a GET request, return dict representations of the API
        polls = Topics.query.filter_by(status=True).join(Polls)\
                .order_by(Topics.id.desc()).all()

        all_polls = {'Polls': [poll.to_json() for poll in polls]}

        return jsonify(all_polls)
Exemple #6
0
def api_polls():
    if request.method == "POST":
        # get the poll and save it in the database
        poll = request.get_json()

        # simple validation to check if all values are properly secret
        for key, value in poll.items():
            if not value:
                return jsonify(
                    {"message": "value for {} is empty".format(key)})

        title = poll["title"]
        options_query = lambda option: Options.query.filter(
            Options.name.like(option))

        options = [
            Polls(option=Options(
                name=option)) if options_query(option).count() == 0 else Polls(
                    option=options_query(option).first())
            for option in poll["options"]
        ]

        new_topic = Topics(title=title, options=options)

        db.session.add(new_topic)
        db.session.commit()

        # run the task
        from tasks import close_poll

        eta = datetime.utcfromtimestamp(poll['close_date'])
        close_poll.apply_async((new_topic.id), eta=eta)

        return jsonify({"message": "Poll was created succesfully"})

    else:
        # it's a GET request, return dict representations of the API
        polls = (Topics.query.filter_by(status=1).join(Polls).order_by(
            Topics.id.desc()).all())
        all_polls = {"Polls": [poll.to_json() for poll in polls]}

        return jsonify(all_polls)
Exemple #7
0
def api_polls():
    if request.method == 'POST':
        # get the poll and save it in the database
        poll = request.get_json()

        # simple validation to check if all values are properly secret
        for key, value in poll.items():
            if not value:
                return jsonify(
                    {'message': 'value for {} is empty'.format(key)})
        title = poll['title']
        options_query = lambda option: Options.query.filter(
            Options.name.like(option))
        """The list comprehension reads as follows Make a Poll object out of an option if that option doesn’t exist 
        in the database (count == 0), if exists in the database (else) then get that option and make a Poll object 
        from it. """
        options = [
            Polls(option=Options(
                name=option)) if options_query(option).count() == 0 else Polls(
                    option=options_query(option).first())
            for option in poll['options']
        ]

        eta = datetime.utcfromtimestamp(poll['close_date'])
        new_topic = Topics(title=title, options=options, close_date=eta)

        db.session.add(new_topic)
        db.session.commit()

        # run the task
        from tasks import close_poll
        close_poll.apply_async((new_topic.id, ), eta=eta)

        return jsonify({'message': 'Poll was created successfully'})

    else:
        # it's a GET request, return dict representations of the API
        polls = Topics.query.filter_by(status=True).join(Polls).order_by(
            Topics.id.desc()).all()
        all_polls = {'Polls': [poll.to_json() for poll in polls]}

        return jsonify(all_polls)
Exemple #8
0
def api_polls():
    if request.method == 'POST':

        poll = request.get_json()

        for key, value in poll.items():
            if not value:
                return jsonify({'message': 'vacia'.format(key)})

        title = poll['title']
        options_query = lambda option: Options.query.filter(
            Options.name.like(option))

        options = [
            Polls(option=Options(
                name=option)) if options_query(option).count() == 0 else Polls(
                    option=options_query(option).first())
            for option in poll['txtOptions']
        ]

        try:
            new_topic = Topics(title=title, options=options)
            db.session.add(new_topic)
            db.session.commit()
        except exc.SQLAlchemyError:
            db.session.rollback()
            return jsonify({
                'message':
                'Existe un problema con nuestra base de datos, favor de intentarlo mas tarde'
            })
            raise
        finally:
            return jsonify({'message': 'Encuesta creada correctamente'})

    else:

        polls = Topics.query.join(Polls).all()
        all_polls = {'Polls': [poll.to_json() for poll in polls]}

        return jsonify(all_polls)
Exemple #9
0
def new_poll(request):
    if request.method == "POST":
        option_list = request.POST.getlist('option[]')
        error = []
        options = []
        error2 = []
        if len(option_list) > 10:
            error2.append(u'Слишком много вариантов, хакир')
        if len(option_list) < 2:
            error2.append(u'Слишком мало вариантов, хакир')
        print len(option_list)
        print len(error2)
        for key, value in enumerate(option_list):
            if len(value) < 2 or len(value) > 15:
                error.append(key)
            options.append([key, value])
        if len(error) > 0 or len(error2) > 0:
            c = Context({
                'user': request.user,
                'head_menu': 'vote_new',
                'error': error,
                'error2': error2,
                'options': options,
                'post': 1,
                'poll_name': request.POST.get('poll_name')
            })
            c.update(csrf(request))
            return render_to_response('new_poll.html', c)
        else:
            poll = Polls()
            poll.user = request.user
            poll.name = request.POST.get('poll_name')
            poll.save()

            last_id = Polls.objects.latest('id')

            for key, value in options:
                option = Options()
                option.poll = last_id
                option.name = value
                option.count = 0
                option.save()
                cache.delete('all_polls')
            return HttpResponseRedirect('/poll/%s/' % (last_id.id))
    else:
        options = []
        [options.append(i) for i in xrange(1, 6)]
        c = Context({
            'user': request.user,
            'head_menu': 'vote_new',
            'options': options
        })
        c.update(csrf(request))
        return render_to_response('new_poll.html', c)
Exemple #10
0
def api_polls():
    if request.method == 'POST':
        poll = request.get_json()
        for key, value in poll.items():
            if not value:
                return jsonify({"message": "ERROR: value for {} is empty".format(key)})
        title = poll['title']
        options_query = lambda option : Options.query.filter(Options.name.like(option))
        options = [Polls(option=Options(name=option)) if options_query(option)==0 else Polls(option=options_query(option).first()) for option in poll['options']]
        new_topic = Topics(title=title, options=options)

        db.session.add(new_topic)
        db.session.commit()
        return jsonify({'message':'Poll was created successfuly'})
    else:
        polls = Topics.query.join(Polls).all()
        all_polls = {'Polls': [poll.to_json() for poll in polls]}
        return jsonify(all_polls)
Exemple #11
0
def add_option():
    new_option = request.args.get('new_option', type=str)
    topic_id = request.args.get('topic_id', type=str)
    topic = Topics.query.filter_by(title=topic_id).first()

    option_temp = Options(new_option)
    db.session.add(option_temp)
    db.session.commit()
    poll_temp = Polls(topic.id, option_temp.id)
    db.session.add(poll_temp)
    db.session.commit()
    
    all_options = Polls.query.filter_by(topic_id=topic.id).all()
    ret_options = {}
    for i in all_options:
        ret_options["id"] = i.id
        ret_options["name"] = i.option.name

    return jsonify(result=ret_options)
def poll_maker(user_id):

    json = request.get_json()

    property_check = [
        'poll_question', 'poll_description', 'option1', 'option2'
    ]
    missing_props = []
    empty_props = []
    for prop in property_check:
        if prop not in json:
            missing_props.append(prop)
    if len(missing_props) > 0:
        raise APIException(
            f'Missing {", ".join(missing_props)} property in json')

    for prop in property_check:
        if json[prop] == "":
            empty_props.append(prop)
    if len(empty_props) > 0:
        raise APIException(f'Missing {", ".join(empty_props)} data in json')

    client = Users.query.get(user_id)
    if client is None:
        raise APIException(f'User not found: 404')

    db.session.add(
        Polls(poll_question=json['poll_question'],
              creator_user_id=user_id,
              poll_description=json['poll_description'],
              info_link=json['info_link'],
              image_link=json['image_link'],
              option1=json['option1'],
              option2=json['option2'],
              option3=json['option3'],
              option4=json['option4']))
    db.session.commit()
    return jsonify(json)
def run():

    Chats.query.delete(
    )  #Arrange the deletes in the opposite order of the models
    Voters_Table.query.delete()
    Polls.query.delete()
    Users.query.delete()

    # MYSQL database for gitpod
    db.session.execute("ALTER TABLE chats AUTO_INCREMENT = 1")
    db.session.execute("ALTER TABLE polls AUTO_INCREMENT = 1")
    db.session.execute("ALTER TABLE users AUTO_INCREMENT = 1")
    db.session.execute("ALTER TABLE voters_table AUTO_INCREMENT = 1")

    # POSTGRES database for heroku
    # db.session.execute("ALTER SEQUENCE chats_id_seq RESTART")
    # db.session.execute("ALTER SEQUENCE polls_id_seq RESTART")
    # db.session.execute("ALTER SEQUENCE users_id_seq RESTART")
    # db.session.execute("ALTER SEQUENCE voters_table_id_seq RESTART")

    now = datetime.utcnow()

    ##################
    #     USERS
    ##################
    Issac = Users(first_name='Issac',
                  last_name='Alleyne',
                  username='******',
                  password=utils.sha256('Awesom3'),
                  date_of_birth='10/22/1994',
                  email='*****@*****.**')
    db.session.add(Issac)
    Naz = Users(first_name='Nhinhoshxhy',
                last_name='Desprez',
                username='******',
                password=utils.sha256('HHH'),
                date_of_birth='1/2/1999',
                email='*****@*****.**')
    db.session.add(Naz)
    Chouerlee = Users(first_name='Chouerlee',
                      last_name='Victor',
                      username='******',
                      password=utils.sha256('Fry'),
                      date_of_birth='10/12/1997',
                      email='*****@*****.**')
    db.session.add(Chouerlee)
    Zion = Users(first_name='Zion',
                 last_name='Raymond',
                 username='******',
                 password=utils.sha256('Zee'),
                 date_of_birth='1/33/1998',
                 email='*****@*****.**')
    db.session.add(Zion)
    Rajae = Users(first_name='Rajae',
                  last_name='Lindsay',
                  username='******',
                  password=utils.sha256('$$'),
                  date_of_birth='4/4/1996',
                  email='[email protected]')
    db.session.add(Rajae)
    Anthony = Users(first_name='Anthony',
                    last_name='Smith',
                    username='******',
                    password=utils.sha256('Dez'),
                    date_of_birth='1/23/1995',
                    email='*****@*****.**')
    Hernan = Users(first_name='Hernan',
                   last_name='Garcia',
                   username='******',
                   password=utils.sha256('geek'),
                   date_of_birth='5/17/1984',
                   email='*****@*****.**')
    db.session.add(Hernan)
    Ms_Achille = Users(first_name='Classified',
                       last_name='Achille',
                       username='******',
                       password=utils.sha256('off-center'),
                       date_of_birth='5/17/1978',
                       email='*****@*****.**')
    db.session.add(Ms_Achille)

    ##################
    #     POLLS
    ##################
    db.session.add(
        Polls(
            creator_user=Chouerlee,
            poll_question="What's the best way to travel?",
            poll_description=
            "A luxury cruise, flying first class, a glamourous bullet train, a scenic drive through the country; which getaway sounds best to you?",
            info_link="",
            image_link=
            "https://images.pexels.com/photos/776030/pexels-photo-776030.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
            option1="Boat",
            option2="Plane",
            option3="Train",
            option4="Drive Myself"))
    db.session.add(
        Polls(
            creator_user=Issac,
            poll_question="Is the government hiding aliens in area 51?",
            poll_description=
            "If there were aliens, we'd know about it now, right? Or would we?",
            info_link="",
            image_link=
            "https://images.pexels.com/photos/365625/pexels-photo-365625.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
            option1="I'm a believer",
            option2="Conspiracy Theories aren't my thing",
            option3="The Government is hiding something, just not aliens",
            option4="The Government would never lie to us. Ever."))
    db.session.add(
        Polls(
            creator_user=Naz,
            poll_question="Should the drinking age be lowered to 18?",
            poll_description=
            "The drinking age is 21 everywhere in the United States, but are 18 year olds mature enough to drink responsibly?",
            info_link="https://drinkingage.procon.org/",
            image_link=
            "https://images.pexels.com/photos/696218/pexels-photo-696218.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
            option1="Yes",
            option2="No, it's fine the way it is",
            option3="It should be raised"))
    db.session.add(
        Polls(
            creator_user=Zion,
            poll_question="Is revenge cheating justified?",
            poll_description=
            "If you're cheated on, you're hurt, angry, and feel disrespected, and rightfully so. But do you cheat back",
            info_link="",
            image_link=
            "https://images.pexels.com/photos/3694011/pexels-photo-3694011.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
            option1="Yes, they have it coming",
            option2="No, two wrongs won't make things right"))
    db.session.add(
        Polls(
            creator_user=Rajae,
            poll_question="Which is the better sport?",
            poll_description=
            "Sports are a part of everyday life, whether you prefer to play, watch or both. These three are some of the most popular in America, so how do they stack against each other?",
            info_link="",
            image_link=
            "https://i2.wp.com/digiday.com/wp-content/uploads/2014/10/naenae.gif?resize=320%2C240&ssl=1",
            option1="Football. The American Version",
            option2="Basketball",
            option3="Baseball; there's a reason it's called America's Pastime.",
            option4="I don't really watch these"))
    db.session.add(
        Polls(
            creator_user=Anthony,
            poll_question="What element would you want to control?",
            poll_description=
            "Manipulating the elements is a standard superpower to have, but often quite powerful. If you could choose one of these four elements, which would you master?",
            info_link="",
            image_link=
            "https://images.pexels.com/photos/1118873/pexels-photo-1118873.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
            option1="Water",
            option2="Earth",
            option3="Fire",
            option4="Air"))
    db.session.add(
        Polls(
            creator_user=Hernan,
            poll_question=
            "If you could travel in time, what would you want to see?",
            poll_description=
            "A world far off or long forgotten, time travel has much appeal, but is it for you?",
            info_link="",
            image_link=
            "https://images.pexels.com/photos/552598/pexels-photo-552598.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
            option1="The past",
            option2="The future",
            option3="There is enough in the present"))
    db.session.add(
        Polls(
            creator_user=Ms_Achille,
            poll_question=
            "If you could have one of these superpowers, which one would you choose?",
            poll_description=
            "We've all dreamt of having superpowers and being more than ordinary; which of these abilities fits you best?",
            info_link="",
            image_link=
            "https://images.pexels.com/photos/346796/pexels-photo-346796.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
            option1="Invisibility",
            option2="Super Strength",
            option3="Flight",
            option4="Telekinesis"))
    db.session.add(
        Polls(
            creator_user=Naz,
            poll_question="Is this website visually appealing?",
            poll_description=
            "The person who designed it went crazy on every little detail, but honestly you don't have to like it, tell us what you think.",
            info_link="",
            image_link=
            "https://images.pexels.com/photos/57690/pexels-photo-57690.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
            option1="It looks very good",
            option2="It's okay",
            option3="Not great, TBH",
            option4="I honestly don't care"))

    ##################
    #  VOTERS_TABLE
    ##################

    db.session.add(
        Voters_Table(user_id=1,
                     poll_id=1,
                     username="******",
                     poll_name="What's the best way to travel?",
                     option_picked="Boat"))
    db.session.add(
        Voters_Table(user_id=2,
                     poll_id=1,
                     username="******",
                     poll_name="What's the best way to travel?",
                     option_picked="Boat"))
    db.session.add(
        Voters_Table(user_id=3,
                     poll_id=1,
                     username="******",
                     poll_name="What's the best way to travel?",
                     option_picked="Plane"))
    db.session.add(
        Voters_Table(user_id=4,
                     poll_id=1,
                     username="******",
                     poll_name="What's the best way to travel?",
                     option_picked="Drive Myself"))
    db.session.add(
        Voters_Table(user_id=5,
                     poll_id=1,
                     username="******",
                     poll_name="What's the best way to travel?",
                     option_picked="Boat"))
    db.session.add(
        Voters_Table(user_id=6,
                     poll_id=1,
                     username="******",
                     poll_name="What's the best way to travel?",
                     option_picked="Plane"))
    db.session.add(
        Voters_Table(user_id=7,
                     poll_id=1,
                     username="******",
                     poll_name="What's the best way to travel?",
                     option_picked="Drive Myself"))
    db.session.add(
        Voters_Table(user_id=8,
                     poll_id=1,
                     username="******",
                     poll_name="What's the best way to travel?",
                     option_picked="Plane"))
    #########################################
    db.session.add(
        Voters_Table(
            user_id=1,
            poll_id=2,
            username="******",
            poll_name="Is the government hiding aliens in area 51?",
            option_picked="The Government is hiding something, just not aliens"
        ))
    db.session.add(
        Voters_Table(user_id=2,
                     poll_id=2,
                     username="******",
                     poll_name="Is the government hiding aliens in area 51?",
                     option_picked="I'm a believer"))
    db.session.add(
        Voters_Table(user_id=3,
                     poll_id=2,
                     username="******",
                     poll_name="Is the government hiding aliens in area 51?",
                     option_picked="Conspiracy Theories aren't my thing"))
    db.session.add(
        Voters_Table(
            user_id=4,
            poll_id=2,
            username="******",
            poll_name="Is the government hiding aliens in area 51?",
            option_picked="The Government would never lie to us. Ever."))
    db.session.add(
        Voters_Table(
            user_id=5,
            poll_id=2,
            username="******",
            poll_name="Is the government hiding aliens in area 51?",
            option_picked="The Government would never lie to us. Ever."))
    db.session.add(
        Voters_Table(user_id=6,
                     poll_id=2,
                     username="******",
                     poll_name="Is the government hiding aliens in area 51?",
                     option_picked="I'm a believer"))
    db.session.add(
        Voters_Table(user_id=7,
                     poll_id=2,
                     username="******",
                     poll_name="Is the government hiding aliens in area 51?",
                     option_picked="I'm a believer"))
    db.session.add(
        Voters_Table(
            user_id=8,
            poll_id=2,
            username="******",
            poll_name="Is the government hiding aliens in area 51?",
            option_picked="The Government is hiding something, just not aliens"
        ))
    ######################################
    db.session.add(
        Voters_Table(user_id=1,
                     poll_id=3,
                     username="******",
                     poll_name="Should the drinking age be lowered to 18?",
                     option_picked="It should be raised"))
    db.session.add(
        Voters_Table(user_id=2,
                     poll_id=3,
                     username="******",
                     poll_name="Should the drinking age be lowered to 18?",
                     option_picked="Yes"))
    db.session.add(
        Voters_Table(user_id=3,
                     poll_id=3,
                     username="******",
                     poll_name="Should the drinking age be lowered to 18?",
                     option_picked="No, it's fine the way it is"))
    db.session.add(
        Voters_Table(user_id=4,
                     poll_id=3,
                     username="******",
                     poll_name="Should the drinking age be lowered to 18?",
                     option_picked="Yes"))
    db.session.add(
        Voters_Table(user_id=5,
                     poll_id=3,
                     username="******",
                     poll_name="Should the drinking age be lowered to 18?",
                     option_picked="No, it's fine the way it is"))
    db.session.add(
        Voters_Table(user_id=6,
                     poll_id=3,
                     username="******",
                     poll_name="Should the drinking age be lowered to 18?",
                     option_picked="No, it's fine the way it is"))
    db.session.add(
        Voters_Table(user_id=7,
                     poll_id=3,
                     username="******",
                     poll_name="Should the drinking age be lowered to 18?",
                     option_picked="Yes"))
    db.session.add(
        Voters_Table(user_id=8,
                     poll_id=3,
                     username="******",
                     poll_name="Should the drinking age be lowered to 18?",
                     option_picked="It should be raised"))
    #######################################
    db.session.add(
        Voters_Table(user_id=1,
                     poll_id=4,
                     username="******",
                     poll_name="Is revenge cheating justified?",
                     option_picked="No, two wrongs won't make things right"))
    db.session.add(
        Voters_Table(user_id=2,
                     poll_id=4,
                     username="******",
                     poll_name="Is revenge cheating justified?",
                     option_picked="Yes, they have it coming"))
    db.session.add(
        Voters_Table(user_id=3,
                     poll_id=4,
                     username="******",
                     poll_name="Is revenge cheating justified?",
                     option_picked="Yes, they have it coming"))
    db.session.add(
        Voters_Table(user_id=4,
                     poll_id=4,
                     username="******",
                     poll_name="Is revenge cheating justified?",
                     option_picked="Yes, they have it coming"))
    db.session.add(
        Voters_Table(user_id=5,
                     poll_id=4,
                     username="******",
                     poll_name="Is revenge cheating justified?",
                     option_picked="No, two wrongs won't make things right"))
    db.session.add(
        Voters_Table(user_id=6,
                     poll_id=4,
                     username="******",
                     poll_name="Is revenge cheating justified?",
                     option_picked="Yes, they have it coming"))
    db.session.add(
        Voters_Table(user_id=7,
                     poll_id=4,
                     username="******",
                     poll_name="Is revenge cheating justified?",
                     option_picked="No, two wrongs won't make things right"))
    db.session.add(
        Voters_Table(user_id=8,
                     poll_id=4,
                     username="******",
                     poll_name="Is revenge cheating justified?",
                     option_picked="Yes, they have it coming"))
    ###########################################
    db.session.add(
        Voters_Table(user_id=1,
                     poll_id=5,
                     username="******",
                     poll_name="Which is the better sport?",
                     option_picked="Football. The American Version"))
    db.session.add(
        Voters_Table(user_id=2,
                     poll_id=5,
                     username="******",
                     poll_name="Which is the better sport?",
                     option_picked="Basketball"))
    db.session.add(
        Voters_Table(user_id=3,
                     poll_id=5,
                     username="******",
                     poll_name="Which is the better sport?",
                     option_picked="I don't really watch these"))
    db.session.add(
        Voters_Table(user_id=4,
                     poll_id=5,
                     username="******",
                     poll_name="Which is the better sport?",
                     option_picked="Basketball"))
    db.session.add(
        Voters_Table(user_id=5,
                     poll_id=5,
                     username="******",
                     poll_name="Which is the better sport?",
                     option_picked="I don't really watch these"))
    db.session.add(
        Voters_Table(user_id=6,
                     poll_id=5,
                     username="******",
                     poll_name="Which is the better sport?",
                     option_picked="Basketball"))
    db.session.add(
        Voters_Table(
            user_id=7,
            poll_id=5,
            username="******",
            poll_name="Which is the better sport?",
            option_picked=
            "Baseball; there's a reason it's called America's Pastime."))
    db.session.add(
        Voters_Table(user_id=8,
                     poll_id=5,
                     username="******",
                     poll_name="Which is the better sport?",
                     option_picked="Football. The American Version"))
    ######################################
    db.session.add(
        Voters_Table(user_id=1,
                     poll_id=6,
                     username="******",
                     poll_name="What element would you want to control?",
                     option_picked="Earth"))
    db.session.add(
        Voters_Table(user_id=2,
                     poll_id=6,
                     username="******",
                     poll_name="What element would you want to control?",
                     option_picked="Air"))
    db.session.add(
        Voters_Table(user_id=3,
                     poll_id=6,
                     username="******",
                     poll_name="What element would you want to control?",
                     option_picked="Water"))
    db.session.add(
        Voters_Table(user_id=4,
                     poll_id=6,
                     username="******",
                     poll_name="What element would you want to control?",
                     option_picked="Water"))
    db.session.add(
        Voters_Table(user_id=5,
                     poll_id=6,
                     username="******",
                     poll_name="What element would you want to control?",
                     option_picked="Fire"))
    db.session.add(
        Voters_Table(user_id=6,
                     poll_id=6,
                     username="******",
                     poll_name="What element would you want to control?",
                     option_picked="Fire"))
    db.session.add(
        Voters_Table(user_id=7,
                     poll_id=6,
                     username="******",
                     poll_name="What element would you want to control?",
                     option_picked="Air"))
    db.session.add(
        Voters_Table(user_id=8,
                     poll_id=6,
                     username="******",
                     poll_name="What element would you want to control?",
                     option_picked="Fire"))
    ######################################
    db.session.add(
        Voters_Table(
            user_id=1,
            poll_id=7,
            username="******",
            poll_name=
            "If you could travel in time, what would you want to see?",
            option_picked="The past"))
    db.session.add(
        Voters_Table(
            user_id=2,
            poll_id=7,
            username="******",
            poll_name=
            "If you could travel in time, what would you want to see?",
            option_picked="There is enough in the present"))
    db.session.add(
        Voters_Table(
            user_id=3,
            poll_id=7,
            username="******",
            poll_name=
            "If you could travel in time, what would you want to see?",
            option_picked="There is enough in the present"))
    db.session.add(
        Voters_Table(
            user_id=4,
            poll_id=7,
            username="******",
            poll_name=
            "If you could travel in time, what would you want to see?",
            option_picked="The past"))
    db.session.add(
        Voters_Table(
            user_id=5,
            poll_id=7,
            username="******",
            poll_name=
            "If you could travel in time, what would you want to see?",
            option_picked="The future"))
    db.session.add(
        Voters_Table(
            user_id=6,
            poll_id=7,
            username="******",
            poll_name=
            "If you could travel in time, what would you want to see?",
            option_picked="The past"))
    db.session.add(
        Voters_Table(
            user_id=7,
            poll_id=7,
            username="******",
            poll_name=
            "If you could travel in time, what would you want to see?",
            option_picked="There is enough in the present"))
    db.session.add(
        Voters_Table(
            user_id=8,
            poll_id=7,
            username="******",
            poll_name=
            "If you could travel in time, what would you want to see?",
            option_picked="The future"))
    ######################################
    db.session.add(
        Voters_Table(
            user_id=1,
            poll_id=8,
            username="******",
            poll_name=
            "If you could have one of these superpowers, which one would you choose?",
            option_picked="Telekinesis"))
    db.session.add(
        Voters_Table(
            user_id=2,
            poll_id=8,
            username="******",
            poll_name=
            "If you could have one of these superpowers, which one would you choose?",
            option_picked="Super Strength"))
    db.session.add(
        Voters_Table(
            user_id=3,
            poll_id=8,
            username="******",
            poll_name=
            "If you could have one of these superpowers, which one would you choose?",
            option_picked="Flight"))
    db.session.add(
        Voters_Table(
            user_id=4,
            poll_id=8,
            username="******",
            poll_name=
            "If you could have one of these superpowers, which one would you choose?",
            option_picked="Flight"))
    db.session.add(
        Voters_Table(
            user_id=5,
            poll_id=8,
            username="******",
            poll_name=
            "If you could have one of these superpowers, which one would you choose?",
            option_picked="Super Strength"))
    db.session.add(
        Voters_Table(
            user_id=6,
            poll_id=8,
            username="******",
            poll_name=
            "If you could have one of these superpowers, which one would you choose?",
            option_picked="Invisibility"))
    db.session.add(
        Voters_Table(
            user_id=7,
            poll_id=8,
            username="******",
            poll_name=
            "If you could have one of these superpowers, which one would you choose?",
            option_picked="Telekinesis"))
    db.session.add(
        Voters_Table(
            user_id=8,
            poll_id=8,
            username="******",
            poll_name=
            "If you could have one of these superpowers, which one would you choose?",
            option_picked="Invisibility"))

    ##################
    #     CHATS
    ##################

    db.session.add(
        Chats(poll_id=1,
              username="******",
              message="'Sup",
              created_at=now + timedelta(minutes=1)))
    db.session.add(
        Chats(poll_id=1,
              username="******",
              message="Konichiwa",
              created_at=now + timedelta(minutes=2)))
    db.session.add(
        Chats(poll_id=1,
              username="******",
              message="Hey",
              created_at=now + timedelta(minutes=3)))
    db.session.add(
        Chats(poll_id=1,
              username="******",
              message="Dude",
              created_at=now + timedelta(minutes=4)))
    db.session.add(
        Chats(poll_id=1,
              username="******",
              message="Yo",
              created_at=now + timedelta(minutes=5)))
    db.session.add(
        Chats(poll_id=1,
              username="******",
              message="Hi",
              created_at=now + timedelta(minutes=6)))
    ############################################
    db.session.add(
        Chats(poll_id=2,
              username="******",
              message="Konichiwa, kolis10",
              created_at=now + timedelta(minutes=1)))
    db.session.add(
        Chats(poll_id=2,
              username="******",
              message="'Sup, Naz",
              created_at=now + timedelta(minutes=2)))
    db.session.add(
        Chats(poll_id=2,
              username="******",
              message="Hi, Curly-Fry",
              created_at=now + timedelta(minutes=3)))
    db.session.add(
        Chats(poll_id=2,
              username="******",
              message="Yo, Coder",
              created_at=now + timedelta(minutes=4)))
    db.session.add(
        Chats(poll_id=2,
              username="******",
              message="Dude, Rager",
              created_at=now + timedelta(minutes=5)))
    db.session.add(
        Chats(poll_id=2,
              username="******",
              message="Hey, Tony",
              created_at=now + timedelta(minutes=6)))
    db.session.commit()
    return 'seeds ran successfully'
Exemple #14
0
def api_polls():
    if request.method == 'POST':

        # get the poll and save it in the database
        poll = request.get_json()

        # simple validation to check if all values are properly set
        for key, value in poll.items():
            if not value:
                return jsonify(
                    {'message': 'value for {} is empty'.format(key)})

        title = poll['title']
        batch = poll['batch']
        options_query = lambda option: Options.query.filter(
            Options.name.like(option))

        options = [
            Polls(option=Options(
                name=option)) if options_query(option).count() == 0 else Polls(
                    option=options_query(option).first())
            for option in poll['options']
        ]
        eta = datetime.utcfromtimestamp(poll['close_date'])
        new_topic = Topics(title=title,
                           poll_group=batch,
                           options=options,
                           close_date=eta)
        #poll_group = Polls()
        #db.session.add(poll_group)
        db.session.add(new_topic)
        db.session.commit()

        # run the task
        from tasks import close_poll

        close_poll.apply_async((new_topic.id, SQLALCHEMY_DATABASE_URI),
                               eta=eta)

        return jsonify({'message': 'Poll was created succesfully'})

    else:
        # it's a GET request, return dict representations of the API
        user = session['user']
        # print('User:'******'NFKD', user).encode('ascii','ignore')
        # print('UpdatedUser:'******'User Info: ', user_info)
        # user_type = unicodedata.normalize('NFKD', user_info.user_group).encode('ascii','ignore')
        user_type = user_info.user_group

        polls = Topics.query.filter_by(
            status=True,
            poll_group=user_type).join(Polls).order_by(Topics.id.desc()).all()
        all_polls = Topics.query.filter_by(
            status=True,
            poll_group='all').join(Polls).order_by(Topics.id.desc()).all()
        for x in all_polls:
            polls.append(x)
        print(type(polls))
        all_polls = {'Polls': [poll.to_json() for poll in polls]}

        return jsonify(all_polls)
Exemple #15
0
from flask import Blueprint, request, jsonify, session

api = Blueprint('api', 'api', url_prefix='/api')

@api.route('/polls', methods=['GET', 'POST'])
# retrieves/adds polls from/to the database def api_polls():
    if request.method == 'POST':
        # get the poll and save it in the database         poll = request.get_json()
        # simple validation to check if all values are properly secret         for key, value in poll.items():
            if not value:
                return jsonify({'message': 'value for {} is empty'.format(key)})

        title = poll['title']
        options_query = lambda option: Options.query.filter(Options.name.like(option))

        options = [Polls(option=Options(name=option))
                   if options_query(option).count() == 0
                   else Polls(option=options_query(option).first()) for option in poll['options']
                   ]

        new_topic = Topics(title=title, options=options)

        db.session.add(new_topic)
        db.session.commit()

        return jsonify({'message': 'Poll was created succesfully'})

    else:
        # it's a GET request, return dict representations of the API         polls = Topics.query.filter_by(status=1).join(Polls).order_by(Topics.id.desc()).all()
        all_polls = {'Polls':  [poll.to_json() for poll in polls]}
Exemple #16
0
from app import db, app

db.app = app
db.init_app(app)
db.create_all()
from models import Options, Topics, Polls

topic = Topics(title='Which side is going to win the EPL this season')
arsenal = Options(name='Arsenal')
spurs = Options(name='Spurs')
poll = Polls(topic=topic, option=arsenal)
poll1 = Polls(topic=topic, option=spurs)
db.session.add(topic)
db.session.commit()
city = Options(name='Manchester city')
liverpool = Options(name='Liverpool FC')
liverpool = Polls(option=liverpool)
city = Polls(option=city)
new_topic = Topics(title='Whos better liverpool or city', options=[liverpool, city])
db.session.add(new_topic)
db.session.commit()
Exemple #17
0
api = Blueprint('api', 'api', url_prefix='/api')

@api.route('/polls', methods=['GET', 'POST'])
# retrieves/adds polls from/to the database 
def api_polls():
    if request.method == 'POST':
        # get the poll and save it in the database        
     poll = request.get_json()
        # simple validation to check if all values are properly secret        
     for key, value in poll.items():
            if not value:
                return jsonify({'message': 'value for {} is empty'.format(key)})
            title = poll['title']
            options_query = lambda option:Options.query.filter(Options.name.like(option))
options = [Polls(option=Options(name=option))
            if options_query(option).count() == 0
            else 
                Polls(option=options_query(option).first()) 
                for option in poll['options']
                ]
new_topic = Topics(title=title, options=options)
db.session.add(new_topic)
db.session.commit()
return jsonify({'message': 'Poll was created succesfully'})
else:
        # it's a GET request, return dict representations of the API         
polls = Topics.query.filter_by(status=1).join(Polls).order_by(Topics.id.desc()).all()
all_polls = {'Polls':  [poll.to_json() for poll in polls]}
return jsonify(all_polls)