Exemplo n.º 1
0
    def test_polls_page_shows_links_to_all_polls(self):
        #setup polls
        poll1 = Poll(question='6 times 7', pub_date=timezone.now())
        poll1.save()
        poll2 = Poll(question='How is your day', pub_date=timezone.now())
        poll2.save()

        #access polls view
        response = self.client.get(reverse('polls.views.show_all_pools'))
        #check if right template used
        self.assertTemplateUsed(response, 'all_polls.html')

        #check if polls transferred to template
        polls_in_context = response.context['polls']
        self.assertEquals(list(polls_in_context), [poll1, poll2])

        #check if polls displayed on the page
        self.assertIn(poll1.question, response.content)
        self.assertIn(poll2.question, response.content)

        #check if polls has links to individual poll
        self.assertIn(reverse('polls.views.poll', args=[poll1.id]),
                      response.content)
        self.assertIn(reverse('polls.views.poll', args=[poll2.id]),
                      response.content)
Exemplo n.º 2
0
    def post(self):
        import cgi
        pname = cgi.escape(self.request.get('pname'))
        plist = cgi.escape(self.request.get('fields'))
        poll = db.get(db.Key.from_path("Poll", pname))
        if poll:
            #Checks if exists
            self.response.out.write('<html><body>Poll:<pre>')
            self.response.out.write(cgi.escape(self.request.get('pname')))
            self.response.out.write(
                '</pre> wasn\' added: already exists <hr/>back to <a href="/admin/">admin</a></body></html>'
            )
            return

        if len(plist.split(',')) < 2:
            #Validates field list
            self.response.out.write('<html><body>Poll:<pre>')
            self.response.out.write(cgi.escape(self.request.get('pname')))
            self.response.out.write(
                '</pre> wasn\' added: not enough options <hr/>back to <a href="/admin/">admin</a></body></html>'
            )
            return

        poll = Poll(key_name=pname, name=pname, values=plist.split(','))
        poll.put()
        self.response.out.write('<html><body>Poll:<pre>')
        self.response.out.write(cgi.escape(self.request.get('pname')))
        self.response.out.write(
            '</pre> added successfully <hr/>back to <a href="/admin/">admin</a></body></html>'
        )
Exemplo n.º 3
0
    def test_was_published_recently_with_old_poll(self):
        """
            was_published_recently() should return False for polls whose pub_date
            is older than 1 day
"""
        old_poll = Poll(pub_date=timezone.now() - datetime.timedelta(days=30))
        self.assertEqual(old_poll.was_published_recently(), False)
Exemplo n.º 4
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(), True)
Exemplo n.º 5
0
    def test_was_published_recently_with_recent_poll(self):
        """
            was_published_recently() should return True for polls whose pub_date
            is within the last day
"""
        recent_poll = Poll(pub_date=timezone.now() -
                           datetime.timedelta(hours=1))
        self.assertEqual(recent_poll.was_published_recently(), True)
Exemplo n.º 6
0
def poll():
    sender = profiles_dict[request.json['user_id']]
    text = request.json['text']
    options = request.json['options']
    poll_id = str(len(all_polls))
    all_polls[poll_id] = Poll(poll_id, sender, text, options)

    slackbot.broadcast_poll(poll_id, text, options, user_list)
    return make_boolean_response()
Exemplo n.º 7
0
    def get_poll(self, id: str) -> Poll:
        response = self.poll_table.get_item(Key={
            "id": id,
            "SK": "poll_info"
        })["Item"]

        return Poll(
            response["id"],
            datetime.fromisoformat(response["date"]),
            response["question"],
            response["result"],
            response.get("user"),
        )
Exemplo n.º 8
0
    def test_creating_a_new_poll_and_saving_it_to_the_database(self):
        poll = Poll()
        poll.question = "What's up?"
        poll.pub_date = timezone.now()

        poll.save()

        all_polls_from_db = Poll.objects.all()
        self.assertEquals(len(all_polls_from_db), 1)
        first_poll_from_db = all_polls_from_db[0]
        self.assertEquals(first_poll_from_db, poll)

        self.assertEquals(first_poll_from_db.question, "What's up?")
        self.assertEquals(first_poll_from_db.pub_date, poll.pub_date)
Exemplo n.º 9
0
    def get_all_polls(self) -> List[Poll]:
        response = self.poll_table.scan(IndexName=self.main_page_gsi)["Items"]
        polls = []

        for poll in response:
            poll = Poll(
                poll["id"],
                datetime.fromisoformat(poll["date"]),
                poll["question"],
                poll["result"],
            )
            polls.append(poll)

        return polls
Exemplo n.º 10
0
def createPoll(request):
    if not request.POST:
        folders = utils.getDateList()
        if utils.getNowH() >= utils.dinnerH:
            meal = "dinner"
        else:
            meal = "lunch"
        return render_to_response("createpoll.html", {
            "folders": folders,
            "meal": meal
        })
    codeLen = 8
    codeChars = string.ascii_uppercase + string.ascii_lowercase + string.digits
    code = ""
    while True:
        code = "".join(random.choice(codeChars) for _ in range(codeLen))
        if not Poll.objects.filter(code=code):
            break
    owner = utils.escapeHtml(request.POST["owner"])
    if not owner:
        owner = utils.getMaskedIp(request)
    title = utils.escapeHtml(request.POST["title"])
    if not title:
        title = "%s's poll" % owner
    open = "open" in request.POST
    p = Poll(owner=owner,
             title=title,
             open=open,
             parent=utils.getToday(),
             code=code,
             count=0)
    result = {}
    result["0_-1"] = []  # any
    result["9_-1"] = []  # 9 any
    result["22_-1"] = []  # 22 any
    lunch9, lunch22, dinner9, dinner22 = utils.getFileLists()
    if utils.getNowH() >= utils.dinnerH:
        dish9 = [int(x.split(".")[0]) for x in dinner9]
        dish22 = [int(x.split(".")[0]) for x in dinner22]
    else:
        dish9 = [int(x.split(".")[0]) for x in lunch9]
        dish22 = [int(x.split(".")[0]) for x in lunch22]
    for d in dish9:
        result["9_" + str(d)] = []
    for d in dish22:
        result["22_" + str(d)] = []
    p.result = json.dumps(result)
    p.save()
    return redirect("/poll/%s/" % code)
Exemplo n.º 11
0
 def addVote(self, request, page):
     user = auth.get_user(request)
     film = Film.objects.get(id=page)
     if not user.is_anonymous:
         user = CustomUser.objects.get(user=user)
         if self.is_valid():
             poll = Poll()
             poll.user = user
             poll.film = film
             poll.mark = self.cleaned_data.get("vote")
             poll.save()
             return False
         else:
             mistake = u"Форма заполнена с ошибками"
             return mistake
Exemplo n.º 12
0
    def post(self, *args):
        logging.info(self.request.arguments())
        name = self.request.get('name')
        start_time = parse(self.request.get('start_time'))
        duration = int(self.request.get('duration'))
        logging.info(name)
        party = politicalparties.all_parties[self.request.get(
            'political_party')]

        poll = Poll(name=name, start_time=start_time, duration=duration)
        logging.info(poll.start_time)
        poll.start_time = poll.start_time.replace(
            tzinfo=gettz('Europe/London'))
        poll.save()

        poll.create_choice(party['id'], party['short_name'], party['colour'])
        self.redirect("/admin/poll/list")
Exemplo n.º 13
0
def generate():

    # get password, questino and options from POST data
    question = request.form.get("question")
    options = json.loads(request.form.get("options"))["options"]
    password = request.form.get("password")

    # generate entry and new url pid
    poll = Poll(question, options, password)
    db_session.add(poll)
    db_session.flush()
    db_session.commit()

    # return url pid
    resp = jsonify(pid=poll.pid)
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp
Exemplo n.º 14
0
def newpoll():
    if 'username' not in session:
        return redirect(url_for('routes.login'))
    form = NewPollForm()
    if request.method == 'POST':
        if form.validate() == False:
            return render_template('newpoll.html.j2', form=form)
        else:
            options = map(options_dict, form.options.data.split(','))
            user_id = session['uid']
            newpoll = Poll(form.name.data, json.dumps(options), user_id)
            db.session.add(newpoll)
            db.session.commit()
            flash('Poll added.')
            return redirect(url_for('routes.newpoll'))
    elif request.method == 'GET':
        return render_template('newpoll.html.j2', form=form)
Exemplo n.º 15
0
def get_poll_article(request, article_id):
    logged_user = request.user
    article = Article.objects.get(id=article_id)
    polls = logged_user.poll_set.all()
    articles = []
    for poll in polls:
        articles.append(poll.article)

    if article in articles:
        url = urlparse.urljoin('/fire/', article_id)
        return redirect(url)
    else:
        article.poll_num += 1
        article.save()
        poll = Poll(user=logged_user, article=article)
        poll.save()
        data = {}
        return redirect('/fire/')
Exemplo n.º 16
0
def create_poll(event, context):
    """
    Create a new voting poll

    Example message from frontend:
    {
        "question": "what is that?"
        "choice1": "cat"
        "choice2": "dog"
    }
    """
    logger.info("Creating a new poll")
    logger.info(event)
    body = json.loads(event["body"])
    authorizer = event["requestContext"]["authorizer"]["jwt"]

    poll = Poll(
        f"poll_{uuid.uuid4()}",
        datetime.now(),
        body["question"],
        Counter({
            body["choice1"]: 0,
            body["choice2"]: 0
        }),
        authorizer["claims"]["username"],
    )
    db.insert_poll(poll)

    msg = {
        "status": "success",
        "message": f"poll {poll.id} is created",
        "poll_id": poll.id,
    }

    return {
        "statusCode": 200,
        "headers": {
            "content-type": "application/json"
        },
        "body": json.dumps(msg),
    }
Exemplo n.º 17
0
def create_a_poll(request, survey_id):
    # create a poll in a survey
    # get questions from input
    # redirect to craetPollPage

    logging.debug(request.POST)
    question = request.POST['Question0']
    choice_list = request.POST.getlist('Field1')
    s = get_object_or_404(Survey, pk=survey_id)
    # check if user correct
    if not s.author == request.user.username:
        return

    p = Poll(survey=s, question=question)
    p.save()
    # get choice from form input
    logging.debug(choice_list)
    for c in choice_list:
        if c:
            logging.debug(c)
            choice = Choice(poll=p, choice=c, votes=0)
            choice.save()

    return HttpResponseRedirect('createPollPage')
Exemplo n.º 18
0
 def post(self):
     parsed_args = poll_parser.parse_args()
     poll = Poll(name=parsed_args['name'], options=parsed_args['options'])
     session.add(poll)
     session.commit()
     return poll, 201
Exemplo n.º 19
0
from django.shortcuts import render
from django.views.generic import TemplateView  #
# Create your views here.
'''from django.http import HttpResponse
def  TestView(request, **kwargs):
	return HttpResponse("Hello Word")'''

from mongoengine import *
#connect("datascience")
from models import Poll
poll = Poll(question="What is your name", )
poll.save()


#print poll.question
class SplashView(TemplateView):
    template_name = "index.html"
Exemplo n.º 20
0
    # Get other attributes
    title = details.get('type').get('name')
    company_code = details.get('company').get('code')
    if company_code == 'SMONKEY': company_code = 'SMNKEY'
    client = details.get('client')
    if not client: client = None

    category = details.get('type').get('canonical')
    url = details.get('tablesurl')
    if not url: url = None  # Because url not always there

    company_model = Company.query.get(company_code)
    poll_model = Poll(id=id,
                      date=utc_date_obj,
                      url=url,
                      category=category,
                      title=title,
                      client=client,
                      company_code=company_code)

    parties = details.get('headline')
    for party in parties:
        party_details = parties.get(party)
        print(poll)
        if not party: party = 'OTH'
        score = party_details.get('pct')

        pp_model = PollParty(score=score)
        party_model = Party.query.get(party)
        pp_model.party = party_model
        poll_model.parties.append(pp_model)
Exemplo n.º 21
0
db = get_db()


# Check if the DB file exists, if not, create it
if not os.path.isfile("db.sqlite"):
    create_db()

    # Lets add some sample data too

    u = User()
    u.displayname = "Testkonto 1"
    u.email = "*****@*****.**"
    u.password = "******"
    u.save()

    p1 = Poll()
    p1.name = "Testpoll 1"
    p1.number = "+46766862842"
    p1.allow_duplicate_answers = True
    p1.allow_multiple_choices = True
    p1.owner = u
    p1.save()

    c1 = Choice()
    c1.poll = p1
    c1.name = "01"
    c1.description = "Bidrag nr. 1 - Bä bä vita lamm"
    c1.save()

    c2 = Choice()
    c2.poll = p1