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>' )
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)
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')
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)
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)
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)
def post(self): question = self.request.get('question') poll = Poll() poll.question = question if users.get_current_user(): poll.author = users.get_current_user() poll.put() self.redirect('/')
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)
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)
def on_message(self, message): print("Message recieved: {}".format(message)) data = {} try: data = json.loads(message) except: self.write_message(json.dumps({"error": "not valid json"})) if "subscribe_poll" in data.keys(): poll = Poll.get_or_none(Poll.id == data["subscribe_poll"]) if not poll: self.write_message( json.dumps({ "result": "error", "message": "unable to find poll with id: {}".format( data["subscribe_poll"]) })) else: self.subscriptions.append(poll) if poll.id not in clients.keys(): clients[poll.id] = [] clients[poll.id].append(self) r = { 'type': 'response', 'response': 'success', 'message': "subscribed to poll {}".format(poll.id) } self.write_message(json.dumps(r)) send_update(poll, self) else: self.write_message(json.dumps({"error": "unknown command"}))
def post(self, year): poll = Poll.get(year) if not poll: self.response.out.write('No poll for ' + year + '.') return poll.flush() self.response.out.write('Flushed.')
async def create_poll(self, ctx, duration, *, title): """ Allows a user to create a poll. """ duration = await self.parse_time_as_delta(duration) if not duration: await ctx.send("Poll must have a valid duration " "that is greater than zero") return end_date = ut.get_utc_time() + duration embed = await self.create_poll_embed(title, end_date, False) message = await ctx.send(embed=embed) # Adds control emojis for emoji in POLL_CONTROL_EMOJI: await message.add_reaction(emoji) # Deletes the original command message await ctx.message.delete() poll = Poll.create(title=title, creator_id=ctx.author.id, message_id=message.id, channel_id=message.channel.id, end_date=end_date) await self.update_response_counts(poll)
def add(request): if not request.user.id: return redirect('/accounts/login?flag=1') if request.POST: poll = Poll(question=request.POST.get('question')) poll.save() for ch in request.POST.getlist('choice'): choice = Choice(poll=poll, choice=ch) choice.save() poll_list = Poll.objects.all() return render_to_response('index.html',dict(poll_list=poll_list, msg_success='Successfully submitted poll and choices')) else: return render(request,'add.html',{})
def get(self): user = users.get_current_user() if user: polls = Poll.all() self.response.write(render('index.html', {'polls': polls})) else: self.redirect(users.create_login_url(self.request.uri))
def get(self, key): user = users.get_current_user() if user: poll = Poll.get(key) self.response.write(poll.question) else: self.redirect(users.create_login_url(self.request.uri))
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/')
async def poll_daemon(self): """ Task loop that update response counts and ends polls that need to be ended """ ongoing_polls = Poll.where('ended', False).get() for poll in ongoing_polls: if ut.get_utc_time() >= poll.end_date: await self.end_poll(poll)
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()
def get(self, year): poll = Poll.get(year) if not poll: self.response.out.write('No poll for ' + year + '.') return unc = [] for b in poll.ballots(): unc.extend(Vote.gql('WHERE ballot = :1 AND release = :2', b, None)) unc.sort(key=lambda v: v.artist.lower()) self.render('admin.html', poll=poll, unc=unc)
async def query_getter(user): query = Poll.join('users', 'polls.creator_id', '=', 'users.id') \ .where('users.guild_id', user.guild.id) if title: query = query.where('polls.title', 'like', f'%{title}%') if not ut.is_admin(user): query = query.where('users.id', user.id) return query
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)
async def on_poll_react(self, payload): """ Listens for reactions to poll messages """ # Ignores if any bots reacts if payload.member.bot: return # Ignores react if the message doesn't correspond to a poll message_id = payload.message_id poll = Poll.where('message_id', message_id).first() if not poll: return channel = self.bot.get_channel(payload.channel_id) try: message = await channel.fetch_message(message_id) except discord.errors.NotFound: return user = payload.member emoji = payload.emoji if emoji.name == DELETE_POLL_EMOJI: deleted = await self.user_delete_poll(poll, message, user) if not deleted: await message.remove_reaction(emoji, user) return # New responses after the poll has ended are not accepted end_date = poll.end_date if ut.get_utc_time() >= end_date or poll.ended: try: await message.remove_reaction(emoji, user) except discord.errors.NotFound: pass return if emoji.name == ADD_CHOICE_EMOJI: await self.get_new_choice_from_user(poll, message, user) elif emoji.name == END_POLL_EMOJI: await self.user_end_poll(poll, message, user) else: choice = poll.choices().where('reaction', str(emoji)).first() await self.toggle_poll_response(choice, message, user) try: await message.remove_reaction(emoji, user) except discord.errors.NotFound: pass if emoji.name not in POLL_CONTROL_EMOJI: await self.update_response_counts(poll)
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"), )
def get(self, year, name): poll = Poll.get(year) if not poll: self.response.out.write('No poll results for ' + year + '.') return name = name or 'results' rendered = getattr(poll, name) if not rendered: rendered = self.getRendered(name + '.html', poll=poll, time=time.ctime()) setattr(poll, name, rendered) poll.put() self.response.out.write(rendered)
def post(self): new_poll = Poll() new_poll.question = self.request.get('question') new_poll.total_votes = 0 new_poll.choices = [ Choice(id=ndb.Key(Choice,c).urlsafe(), choice=c, votes=0) for c in self.request.POST.getall('choice') if c ] new_poll.put() url = '/poll/' + new_poll.key.urlsafe() self.response.write('<pre>@ <a href="' + url + '">' + url + '</a></pre>')
class PollModelTestCase(Chai, TestCase): def setUp(self): super(PollModelTestCase, self).setUp() self.subject = Poll() def test_is_visable(self): now = datetime.datetime.now() dt = self.mock() mock_dt = self.mock(models, 'datetime') self.expect(mock_dt.now).returns(now) self.subject.publish_date = now assert self.subject.is_visable() def test_is_not_visable(self): now = datetime.datetime.now() dt = self.mock() mock_dt = self.mock(models, 'datetime') self.expect(mock_dt.now).returns(now) self.subject.publish_date = now - datetime.timedelta(days=10) assert not self.subject.is_visable()
def get(self, pollname): logging.info("Editing poll: " + pollname) poll = Poll.get_by_name(pollname) poll.start_time = models.get_time_as_local(poll.start_time) logging.info("Got poll from datastore: %s " % (poll)) template = jinj.get_template('poll_create.html') return template.render({ 'politicalparties': politicalparties.all(), 'start_time': poll.start_time, 'name': poll.name, 'duration': poll.duration, 'edit': True })
def get_all_votes(event, context): """ Get most recent polls from ddb """ logger.info("get all polls") polls = db.get_all_polls() return { "statusCode": 200, "headers": { "content-type": "application/json" }, "body": Poll.schema().dumps(polls, many=True), }
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
def get(self, pollname): logging.info("Editing poll: "+pollname) poll = Poll.get_by_name(pollname) poll.start_time = models.get_time_as_local(poll.start_time) logging.info("Got poll from datastore: %s " % (poll)) template = jinj.get_template('poll_create.html') return template.render({ 'politicalparties': politicalparties.all(), 'start_time': poll.start_time, 'name': poll.name, 'duration': poll.duration, 'edit': True })
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')
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
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)
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
async def summon_poll(self, ctx, poll_id: int): """ Allows a user to bring forward a poll in the conversation, for the benefit of longer-duration polls """ poll = Poll.find(poll_id) if not poll: await ctx.send(f"Poll with ID {poll_id} could not found.") return if ctx.author.id != poll.creator_id and not ut.is_admin(ctx.author): await ctx.send("You don't have permission to summon that poll!") return old_channel = self.bot.get_channel(poll.channel_id) try: old_message = await old_channel.fetch_message(poll.message_id) await old_message.delete() except discord.errors.NotFound: pass embed = await self.create_poll_embed(poll.title, poll.end_date, poll.ended) new_message = await ctx.send(embed=embed) if not poll.ended: await new_message.add_reaction(ADD_CHOICE_EMOJI) await new_message.add_reaction(DELETE_POLL_EMOJI) if not poll.ended: await new_message.add_reaction(END_POLL_EMOJI) for choice in poll.choices: await new_message.add_reaction(choice.reaction) await ctx.message.delete() poll.message_id = new_message.id poll.channel_id = ctx.channel.id poll.save() await self.update_response_counts(poll)
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")
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)
def post(self): try: sms = {} sms["to"] = self.get_argument("to") sms["from"] = self.get_argument("from") sms["message"] = self.get_argument("message") poll = Poll.get_or_none(Poll.number == sms["to"]) if not poll: self.write("No poll with that number") else: if poll.add_answer(sms["message"], sms["from"]): self.write("Success") update_all_pollclients(poll) else: self.write("Failed to add answer") except Exception as e: print(e) self.write("Failed tot parse request") self.finish()
def get(self): user = users.get_current_user() if user: if users.is_current_user_admin(): template_values = {} polls = Poll.gql("ORDER BY name DESC") template_values["polls"] = polls apoll = ActivePoll.get_or_insert("key", mkey="activepoll") try: currentpoll = apoll.poll.name except AttributeError: currentpoll = "" #unable to retrieve current poll template_values["currentpoll"] = currentpoll.strip() import os path = os.path.join(os.path.dirname(__file__), 'admin.html') self.response.out.write(template.render(path, template_values)) else: self.abort(403) else: self.redirect(users.create_login_url(self.request.uri))
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), }
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")
def validate(self): user = users.get_current_user() self.logout = users.create_logout_url(self.request.uri) self.voter = Voter.gql('WHERE user = :1', user).get() if not self.voter: return 'invalid' self.years = Poll.openYears() if not self.years: return 'closed' defaultYear = max(self.years) self.year = int(self.request.get('year') or self.voter.year or defaultYear) if self.year not in self.years: self.year = defaultYear if self.voter.year != self.year: self.voter.year = self.year self.voter.put() self.ballot = Ballot.gql('WHERE voter = :1 and year = :2', self.voter, self.year).get() return None
""" # Create a new database with our models! # ./manage.py syncdb """ LEARNING THE BASICS OF THE ORM """ from polls.models import * from django.utils import timezone # Queryset with all Poll objects in the database Poll.objects.all() p = Poll(question="What up?", pub_date=timezone.now()) p.save() # Let's see the id p.id # There's also an alias p.pk # if you override the primary key name which by default is id # you can still access it by pk. from django.utils import timezone p = Poll(question="What up?", pub_date=timezone.now()) Poll(question="What's not?", pub_date=timezone.now()).save() Poll(question="How's it going?", pub_date=timezone.now()).save()
def get(self): query = Poll.query().order(-Poll.date) polls = query.fetch() self.response.write(render('home.html', { 'latest_poll_list':polls }))
def post(self, year): Poll.get(year).rankReleases() # TO DO: status page (with auto-refresh?) self.redirect('')
def get(self): self.render('admindex.html', polls=Poll.gql('ORDER BY year DESC'))
def get(self): polls = Poll.select() self.render("templates/create_poll.html", polls=polls)
def test_was_published_recently_recent_poll(self): recent_poll = Poll(pub_date=timezone.now() - datetime.timedelta(hours=10)) self.assertEqual(recent_poll.was_published_recently(),True)
def get(self, poll_id): poll = Poll.get_or_none(Poll.id == poll_id) if poll == None: raise tornado.web.HTTPError(404) self.render("templates/poll.html", poll=poll)
def test_was_published_recently_with_future_poll(self): future_poll = Poll(question='Future', pub_date=timezone.now() + datetime.timedelta(days=30)) self.assertEqual(future_poll.was_published_recently(), False)
def test_was_published_recently_with_old_poll(self): old_poll = Poll(question='Old', pub_date=timezone.now() - datetime.timedelta(days=2)) self.assertEqual(old_poll.was_published_recently(), False)
def test_was_published_recently_with_recent_poll(self): recent_poll = Poll(question='Recent', pub_date=timezone.now() - datetime.timedelta(hours=5)) self.assertEqual(recent_poll.was_published_recently(), True)
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
def get(self): self.render('index.html', years=Poll.openYears(), oldyears=range(1995, 2004))
def setUp(self): super(PollModelTestCase, self).setUp() self.subject = Poll()
def test_was_published_recently_future_poll(self): future_poll = Poll(pub_date=timezone.now() + datetime.timedelta(days=20)) self.assertEqual(future_poll.was_published_recently(),False)