def select(carname): user = [] for i in db.session.query(Choice.UserId).all(): user.append(i[0]) if len(user) > 0: for i in user: if current_user.id in user: flash(carname) return render_template('vote.html', select=carname) else: choice = Choice(chooseSeries=carname, UserId=current_user.id, vote=1) db.session.add(choice) db.session.commit() flash("Voted:" + str(carname)) return render_template('vote.html', select=carname, choice=choice) else: choice = Choice(chooseSeries=carname, UserId=current_user.id, vote=1) db.session.add(choice) db.session.commit() flash("Voted:" + str(carname)) return render_template('vote.html', select=carname, choice=choice)
def newpoll(request): """new poll page.""" if request.method == 'POST': form = CreatePollForm(request.POST) if form.is_valid(): Poll = form.save() choice = Choice() choice.poll = Poll choice.text = 'I agree with argument 1' choice.votes = 0 choice.save() choice = Choice() choice.poll = Poll choice.text = 'I agree with argument 2' choice.votes = 0 choice.save() choice = Choice() choice.poll = Poll choice.text = 'Neither argument is compelling' choice.votes = 0 choice.save() return HttpResponseRedirect(reverse('app:home')) else: form = CreatePollForm assert isinstance(request, HttpRequest) return render( request, 'app/newpoll.html', { 'title': 'Submit new case', 'message': 'Your application description page.', 'year': datetime.now().year, 'form': form })
def test_delete(self): #create dummy users user1 = User(username="******", email="*****@*****.**", preference="AS") user1.set_password('password') choice1 = Choice(chooseSeries="Lambo", UserId=1, vote=1) user2 = User(username="******", email="*****@*****.**", preference="Lambo") user2.set_password('password') choice2 = Choice(chooseSeries="Lambo", UserId=2, vote=1) user3 = User(username="******", email="*****@*****.**", preference="GTR") user3.set_password('password') choice3 = Choice(chooseSeries="AS", UserId=3, vote=1) db.session.add(user1) db.session.add(choice1) db.session.add(user2) db.session.add(choice2) db.session.add(user3) db.session.add(choice3) db.session.commit() #login as admin administrator = User(username="******", email="*****@*****.**", preference="AS") administrator.set_password('password') administrator.admin = True db.session.add(administrator) db.session.commit() self.login("admin", "password") #check admin page and database for user1 response = self.app.get('/hoster', follow_redirects=True) self.assertIn(b'user1', response.data) self.assertTrue(User.query.get(1)) #admin deletes user1 self.delete(1) #check admin page and database for user1 response = self.app.get('/hoster', follow_redirects=True) self.assertNotIn(b'user1', response.data) self.assertFalse(User.query.get(1)) #check admin page for votes from user1 (id = 1) self.assertNotIn(b'<td class="active" value="userid">1</td>', response.data)
def index(page): try: db.drop_all() db.create_all() # create quiz maker quiz_maker = User(name='Hassan', email='*****@*****.**', password='******') # create quiz with single-choice questions quiz = Quiz(title="Quiz 1", limited_time=12, posted_at=datetime.now()) # create and add question for the quiz question = Question(content="1+1=?", correct_answer=2, choices=[ Choice(content="1"), Choice(content="2"), Choice(content="3"), Choice(content="4"), ]) quiz.questions.append(question) quiz.questions.append( Question(content="1+2=?", correct_answer=3, choices=[ Choice(content="1"), Choice(content="2"), Choice(content="3"), Choice(content="4"), ])) # add created quiz to quiz maker's created quizzes list quiz_maker.created_quizzes.append(quiz) # create quiz taker quiz_taker = User(name='guest', email='[email protected]', password='******') # quiz taker take a quiz, create user quiz result quiz_result = QuizResult(quiz=quiz) # add quiz result to the taker quiz_taker.quizzes_results.append(quiz_result) # set quiz taker's answer for question[0] in the quiz, here user choose the second choice which is at index 1 user_choice = quiz.questions[0].choices[1] # create a user choice, user_answer = UserChoice(choice=user_choice, answer_right=True) # add the user answer to the quiz result quiz_result.user_choices.append(user_answer) quiz_result.user_choices.append( UserChoice(choice=quiz.questions[1].choices[1], answer_right=False)) # add and commit changes db.session.add(quiz_maker) db.session.add(quiz_taker) db.session.commit() # query all users users = User.query.all() # print(users[1].quizzes_results[0]) return render_template('%s.html' % page, users=users) except Exception as ex: print(ex) abort(404)
def create_quiz(): if 'user' in session and (user := session['user']): form = f.QuizForm(request.form) if request.method == 'POST' and form.validate(): user = User.query.filter_by(email=user.email).first() quiz = Quiz(user=user, limited_time=int(form.limited_time.data), title=form.title.data, access_code=form.access_code.data, visibility=form.visibility.data, questions=[ Question(correct_answer=i['correct_answer'], content=i['content'], choices=[ Choice(content=c["content"]) for c in i['choices'] ]) for i in form.questions.data ]) user.created_quizzes.append(quiz) db.session.add(user) db.session.commit() return redirect(url_for('main.user_profile')) session['quiz'] = { "title": "", "access_code": "", "limited_time": "", "visibility": "Public", "questions": [], } form = f.QuizForm(data=session["quiz"]) return render_template('create_quiz.html', form=form, get_index=get_index, get_index_int=get_index_int)
def test_remove_vote(self): user1 = User(username="******", email="*****@*****.**", preference="AS") user1.set_password('password') choice1 = Choice(chooseSeries="Lambo", UserId=1, vote=1) user2 = User(username="******", email="*****@*****.**", preference="Lambo") user2.set_password('password') choice2 = Choice(chooseSeries="Lambo", UserId=2, vote=1) db.session.add(user1) db.session.add(choice1) db.session.add(user2) db.session.add(choice2) admin = User(username="******", email="*****@*****.**", preference="AS") admin.set_password('password') admin.admin = True db.session.add(choice1) db.session.add(user2) db.session.add(choice2) db.session.add(admin) db.session.commit() #login as admin response = self.login("Grae", "password") #check that the user1 choice exists self.assertIn( b'''<td class="active">user1</td> <td class="active">Lambo</td>''', response.data) #delete user1 choice response = self.delete_user_vote(1) self.assertIn(b'One Vote has been deleted!', response.data) self.assertNotIn( b'''<td class="active">user1</td> <td class="active">Lambo</td>''', response.data) self.assertFalse(Choice.query.get(1)) #check user1 has not been deleted self.assertIn(b'<td class="active">user1</td>', response.data) self.assertTrue(User.query.filter_by(username="******").first())
def make_choice(session, text='sample_choice', correct=False, question=None): if question is None: question = make_question(session) choice = Choice() choice.question_id = question.id choice.text = text choice.correct = correct session.add(choice) session.commit() return choice
def edit_quiz(quiz_id): if 'user' in session and (user := session['user']): quiz = Quiz.query.filter_by(id=quiz_id).first() form = f.QuizForm(request.form) if request.method == 'POST': user = User.query.filter_by(email=user.email).first() quiz.id = quiz.id quiz.title = form.title.data quiz.access_code = form.access_code.data quiz.visibility = form.visibility.data quiz.limited_time = int(form.limited_time.data) for i, question in enumerate(quiz.questions): try: question.content = form.questions.data[i]['content'] question.correct_answer = form.questions.data[i][ 'correct_answer'] for ci, choice in enumerate(question.choices): try: choice.content = form.questions.data[i]['choices'][ ci]['content'] except: db.session.delete(choice) except: db.session.delete(question) if len(quiz.questions) < len(form.questions.data): start = len(form.questions.data) - len(quiz.questions) for i in range(start, len(form.questions.data)): quiz.questions.append( Question(content=form.questions.data[i]['content'], correct_answer=form.questions.data[i] ['correct_answer'], choices=[ Choice(content=c['content']) for c in form.questions.data[i]['choices'] ])) db.session.add(quiz) db.session.commit() return redirect(url_for('main.user_profile')) session["quiz"] = { "title": quiz.title, "access_code": quiz.access_code, "visibility": quiz.visibility, "questions": quiz.questions_dict, "limited_time": quiz.limited_time, } form = f.QuizForm(data=session["quiz"]) return render_template('create_quiz.html', quiz=quiz, form=form, get_index=get_index, get_index_int=get_index_int, is_editing=True)
def AddChoice(eid, choice): if CheckOwner(eid): print('CheckOwner') # Check if choice is already in use or not c = Choice.query.filter_by(election=eid, choice=choice).first() if c is None: print('hello') c = Choice(choice=choice, election=eid) db.session.add(c) db.session.commit() return True else: return False
def choice_course(): data = request.get_json() if data: u_id = data.get('u_id') c_id = data.get('c_id') if u_id and c_id: user = User.query.get_or_404(u_id) course = Course.query.get_or_404(c_id) ch = Choice(user=user, course=course) for video in course.videos: uv = UserVideo.create(user, video) db.session.add(uv) ch.update_nums() return jsonify({'resCode': 'ok', 'msg': '选课成功!'}) return jsonify({'resCode': 'err', 'msg': '选课失败!无数据或数据错误!'})
def create_choice(thid): """Create a choice.""" form = ThreadForm() form["csrf_token"].data = request.cookies["csrf_token"] if form.validate_on_submit(): image_filename = upload_file(form["image"].data) choice = Choice( title=form["title"].data, prev_thread_id=form["prev_thread"].data, next_thread_id=form["next_thread"].data, color=form["color"].data, icon=form["icon"].data, image=image_filename ) db.session.add(choice) db.session.commit() return choice.to_dict() else: return {"errors": validation_errors_to_messages(form.errors)}, 401
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 createChoicesFromString(choices_string, thread): """ Convert json data into new thread_choice records in the database, then return a dictionary compilation of the choices. """ # Create choices that new thread connects to choices_dict = {} choices = json.loads(choices_string) print(choices, choices_string) for choice in choices: # TODO Check if 'choices' is object so as to grab alt title. thread_choice = Choice( title=" ".join(choice.split(" ")[1:]), prev_thread=thread, next_thread_id=int(choice.split(" ")[0]), ) db.session.add(thread_choice) db.session.commit() choices_dict[thread_choice.id] = thread_choice.to_dict() return choices_dict
def createChoices(choices_data, thread): """ Convert json data into new thread_choice records in the database, then return a dictionary compilation of the choices. """ # Create choices that new thread connects to choices = {} for choice in choices_data: # TODO Check if 'choices' is object so as to grab alt title. thread_choice = Choice( title=choice["title"], description=choice["description"], prev_thread=thread, next_thread_id=choice["next_thread_id"], color=choice["color"], icon=choice["icon"], image=choice["image"], ) db.session.add(thread_choice) db.session.commit() choices[thread_choice.id] = thread_choice.to_dict() return choices
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 submit(self, form: models.Form, user, user_agent: UserAgent): """ 提交表单 """ if form.validate(): session = db.session v = form.values() v.assemble_from_user_agent(user_agent) user_id = (user and not user.is_anonymous) and user.id or None v.user_id = user_id # 查找所有的选项字段并保存选择的结果 def find_option_id(field, value): for option in field.options: if value == option.value: return option.id return -1 for field in form.select_fields: for value in field.value: choice = Choice(form_id=form.id, field_id=field.id, option_id=find_option_id( field, value['value']), value=value['value']) session.add(choice) form.increase_value_sequence() v.sequence = form.value_sequence session.add(v) session.commit() return v return None
def index(): if current_user.admin == False: car1 = [] for i in db.session.query(Brand.carSeries).all(): car1.append(i[0]) carVote = {} carname = [] carValue = [] for i in db.session.query(Choice.chooseSeries).all(): carVote[i[0]] = carVote.get(i[0], 0) + 1 sortCarVote = sorted(carVote, key=carVote.get, reverse=True) for i in sortCarVote: carname.append(i) carValue.append(carVote[i]) flash("Voting result " + str(carVote)) user = [] for i in db.session.query(Choice.UserId).all(): user.append(i[0]) if len(user) > 0: for i in user: if current_user.id in user: choice = Choice(chooseSeries=select, UserId=current_user.id, vote=1) flash("current user has voted") break else: flash("not voted yet") choice = Choice(chooseSeries=select, UserId=current_user.id, vote=0) break else: flash("not voted yet") choice = Choice(chooseSeries=select, UserId=current_user.id, vote=0) tableCar = [] tableVote = [] for i in db.session.query(Choice.chooseSeries).all(): tableCar.append(i[0]) for i in db.session.query(Choice.vote).all(): tableVote.append(i[0]) tableUser = [] for i in db.session.query(User).join(Choice): tableUser.append(i) # flash(tableUser) # flash(tableCar) # flash(tableVote) a = zip(tableUser, tableCar, tableVote) return render_template('index.html', title='Home', a=a, car1=car1, carVote=carVote, choice=choice, carname=carname, carValue=carValue) else: flash("You are admin!") return redirect(url_for('hoster'))
def seed_threads(): """Seed a series of connected threads for Demo Tale.""" # Creating the threads, which will be connected via 'choices' next. thread0 = Thread( # 0 title="The Beginning", description= "At the beginning, there were two doors. A red door and a blue door.", color="rgb(70,60,70)", icon="sign", image= "https://res.cloudinary.com/peerspace-inc/image/upload/q_80,c_crop,g_custom/w_2048/hztukpx3k9m3qbezy0ik.jpg", tale_id=1, ) thread1 = Thread( # 1 title="The Red Room", description= "In the red door, there is a room with a bowl of candy and a vase full of lilies, as well as another red door at the far wall.", color="#e05265ff", icon="door-closed", tale_id=1, ) thread2 = Thread( # 2 title="The Blue Room", description= "In the blue door, there is a small red key on the table, as well as another blue door at the far wall.", color="#5a70ccff", icon="door-open", tale_id=1, ) thread3 = Thread( # 3 title="The Joined Room", description= "Looking behind you, you see both a red and blue door. It seems both rooms eventually led to the same destination. In here, you see a glowing fairy angrily throwing a tennis ball at the wall.", color="#4f4686ff", tale_id=1, ) thread4 = Thread( # 4 title="Take Candy", description= "You take the candy and pocket it. They look very delicious.", color="#964a70ff", icon="candy-cane", tale_id=1, ) thread5 = Thread( # 5 title="Smell the Lilies", description="*sniff sniff* They're quite fragrant. How lovely.", color="#f9fbefff", icon="seedling", image= "https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/easter-lily-royalty-free-image-1583439719.jpg", tale_id=1, ) thread6 = Thread( # 6 title="Take Key", description= "You take the little red key and put it in your pocket. This should help you out.", color="#e05265ff", icon="key", tale_id=1, ) thread7 = Thread( # 7 title="Talk to the Sweet Fairy", description= "The fairy bemoans about how hungry it is, and it really wants something sweet to eat.", color="#57768aff", icon="comment", tale_id=1, ) thread8 = Thread( # 8 title="Give Candy", description= "The sweet fairy is very happy, and thanks you with a smile.", color="#e05265ff", icon="candy-cane", tale_id=1, ) thread9 = Thread( # 9 title="Lecture Sweet Fairy About a Healthy Diet", description= "You give the little fairy a stern talking-to about eating its vegetables to grow up healthy and strong. It seems very unhappy with you, and lapses into silence, throwing its ball with even more gusto.", color="#8cb15eff", icon="carrot", tale_id=1, ) thread10 = Thread( title="Look around", description="You look around. Nice.", color="rgb(70,60,70)", icon="eye", image= "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTHWvp2ZW7nv-Kor5411yZ45_iLhmDKphgrTw&usqp=CAU", tale_id=1, is_sequitur=False, ) # thread10 = Thread( # tale_id=1, # title="", # description="") db.session.add(thread0) db.session.add(thread1) db.session.add(thread2) db.session.add(thread3) db.session.add(thread4) db.session.add(thread5) db.session.add(thread6) db.session.add(thread7) db.session.add(thread8) db.session.add(thread9) db.session.add(thread10) db.session.commit() threads = [ thread0, thread1, thread2, thread3, thread4, thread5, thread6, thread7, thread8, thread9, thread10 ] # Adding choice-links between threads with choice-thread default titles. choices = ((0, 1), (0, 2), (1, 4), (1, 5), (2, 6), (3, 7), (7, 8), (7, 9)) for choice in choices: new_choice = Choice(title=threads[choice[1]].title, prev_thread=threads[choice[0]], next_thread=threads[choice[1]]) db.session.add(new_choice) # Adding choices with unique titles new_choice5 = Choice(title="Go through second red door", prev_thread=threads[1], next_thread=threads[3]) new_choice6 = Choice(title="Go through second blue door", prev_thread=threads[2], next_thread=threads[3]) db.session.add(new_choice5) db.session.add(new_choice6) 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])