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()
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)
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)
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)
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)
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)
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)
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'))
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 }
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()
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
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()
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
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)
def hostPoll(): header = "Enter your desired poll!" form = PollForm() if form.validate_on_submit(): # We need to create the session and the poll, then link them # together. sesh = Session(session_id=form.sessionID.data) poll = Poll(question=form.questionText.data) session = Session.query.filter_by( session_id=form.sessionID.data).first() # If the session doesn't exist if not (session is None): flash('Session in use!') return redirect('/host_poll') poll.a = form.a.data poll.b = form.b.data poll.c = form.c.data poll.d = form.d.data poll.a_num = 0 poll.b_num = 0 poll.c_num = 0 poll.d_num = 0 # Link them poll.session = sesh sesh.poll = poll db.session.add(sesh) db.session.commit() db.session.add(poll) db.session.commit() flash("Generating poll!") return redirect('/pollData/' + sesh.session_id) return render_template('create_poll.html', title='Host a Poll', header=header, form=form)
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)
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))
def test_createPoll(self): title='test_createPoll- where is your third favorite fishing spot?' description='test_createPoll- survey to find out the most favorite fishing spot in Perth' user=User() user.userId=1 minResponses=5 #if not specified, the default value is -1 which will be ignored orderCandidateBy=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, orderCandidateBy, isOpenPoll, openAt, closeAt, user) poll.addCandidate('test_createPoll- Narrows Bridge Perth',None) poll.addCandidate('test_createPoll- White Hills Mandurah',None) poll.addCandidate('test_createPoll- North Mole Fremantle',None) poll.addCandidate('test_createPoll- Floreat Drain Floreat',None) poll.addCandidate('test_createPoll- Ricey Beach And Radar Reef Rottnest Island',None) poll.addCandidate('test_createPoll- Lancelin Jetty Lancelin',None) assert_that(createPoll(poll)).is_equal_to(True)
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'))
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 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'))
def setUp(self): # basedir=os.path.abspath(os.path.dirname(__file__)) # SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'test.db') # self.app=app.test_client() self.app=create_app(TestConfig) self.app_context=self.app.app_context() self.app_context.push() db.create_all() luna=User() luna.username='******' luna.firstName='Luna' luna.lastName='Lee' luna.email='*****@*****.**' luna.isAdmin=True haolin=User() haolin.username='******' haolin.firstName='abcHaolin' haolin.lastName='Wu' haolin.email='*****@*****.**' haolin.isAdmin=True db.session.add(luna) db.session.add(haolin) db.session.commit() title='where is your favorite fishing spot?' description='survey to find out the most favorite fishing spot in Perth' user=User.query.filter_by(username='******').first() minResponses=5 #if not specified, the default value is -1 which will be ignored orderCandidateBy=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, orderCandidateBy, isOpenPoll, openAt, closeAt, user) db.session.add(poll) db.session.commit() candidate1 = Poll.Candidate() candidate1.candidateDescription='Narrows Bridge Perth' candidate1.displayOrder=None candidate1.pollId=Poll.query.filter_by(pollId=1).first().pollId candidate1.isActive=True candidate2 = Poll.Candidate() candidate2.candidateDescription='White Hills Mandurah' candidate2.displayOrder=None candidate2.pollId=Poll.query.filter_by(pollId=1).first().pollId candidate2.isActive=True candidate3 = Poll.Candidate() candidate3.candidateDescription='North Mole Fremantle' candidate3.displayOrder=None candidate3.pollId=Poll.query.filter_by(pollId=1).first().pollId candidate3.isActive=True candidate4 = Poll.Candidate() candidate4.candidateDescription='Floreat Drain Floreat' candidate4.displayOrder=None candidate4.pollId=Poll.query.filter_by(pollId=1).first().pollId candidate4.isActive=True candidate5 = Poll.Candidate() candidate5.candidateDescription='Ricey Beach And Radar Reef Rottnest Island' candidate5.displayOrder=None candidate5.pollId=Poll.query.filter_by(pollId=1).first().pollId candidate5.isActive=True candidate6 = Poll.Candidate() candidate6.candidateDescription='Lancelin Jetty Lancelin' candidate6.displayOrder=None candidate6.pollId=Poll.query.filter_by(pollId=1).first().pollId candidate6.isActive=True db.session.add(candidate1) db.session.commit() db.session.add(candidate2) db.session.commit() db.session.add(candidate3) db.session.commit() db.session.add(candidate4) db.session.commit() db.session.add(candidate5) db.session.commit() db.session.add(candidate6) db.session.commit()
def setUp(self): self.app=create_app(TestConfig) self.app_context=self.app.app_context() self.app_context.push() db.create_all() luna=User() luna.username='******' luna.firstName='Luna' luna.lastName='Lee' luna.email='*****@*****.**' luna.isAdmin=True db.session.add(luna) db.session.commit() title='where is your favorite fishing spot?' description='survey to find out the most favorite fishing spot in Perth' user=User.query.filter_by(username='******').first() minResponses=5 #if not specified, the default value is -1 which will be ignored orderCandidateBy=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, orderCandidateBy, isOpenPoll, openAt, closeAt, user) db.session.add(poll) db.session.commit() candidate1 = Poll.Candidate() candidate1.candidateDescription='Narrows Bridge Perth' candidate1.displayOrder=None candidate1.pollId=Poll.query.filter_by(pollId=1).first().pollId candidate1.isActive=True candidate2 = Poll.Candidate() candidate2.candidateDescription='White Hills Mandurah' candidate2.displayOrder=None candidate2.pollId=Poll.query.filter_by(pollId=1).first().pollId candidate2.isActive=True candidate3 = Poll.Candidate() candidate3.candidateDescription='North Mole Fremantle' candidate3.displayOrder=None candidate3.pollId=Poll.query.filter_by(pollId=1).first().pollId candidate3.isActive=True candidate4 = Poll.Candidate() candidate4.candidateDescription='Floreat Drain Floreat' candidate4.displayOrder=None candidate4.pollId=Poll.query.filter_by(pollId=1).first().pollId candidate4.isActive=True candidate5 = Poll.Candidate() candidate5.candidateDescription='Ricey Beach And Radar Reef Rottnest Island' candidate5.displayOrder=None candidate5.pollId=Poll.query.filter_by(pollId=1).first().pollId candidate5.isActive=True candidate6 = Poll.Candidate() candidate6.candidateDescription='Lancelin Jetty Lancelin' candidate6.displayOrder=None candidate6.pollId=Poll.query.filter_by(pollId=1).first().pollId candidate6.isActive=True db.session.add(candidate1) db.session.commit() db.session.add(candidate2) db.session.commit() db.session.add(candidate3) db.session.commit() db.session.add(candidate4) db.session.commit() db.session.add(candidate5) db.session.commit() db.session.add(candidate6) db.session.commit()
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])