def sms_find_poll(): """Find poll from sms""" # Start our response resp = MessagingResponse() sms = request.values['Body'] poll = Poll.get_from_code(sms) # del session['short_code'] if 'short_code' in session: short_code = session['short_code'] poll = Poll.get_from_code(short_code) if poll.poll_type.multi_select: if sms[0].upper() == 'N': del session['short_code'] resp.message('Thank you for responding.') return str(resp) elif sms[0].upper() == 'Y': resp.redirect('/sms/' + short_code) else: resp.message('Please type "Y" for Yes or "N" for No.') resp.redirect('/sms/' + short_code + '/input') elif poll: resp.redirect('/sms/' + sms) else: resp.message('That poll does not exist') return str(resp)
def render_poll(short_code): """Show poll in React.""" poll = Poll.get_from_code(short_code) user = User.get_user() logger.info(session) logger.info(f'poll: {poll}') if poll is not None: # Ensure this is a valid poll route if user.is_admin(poll): logger.info("Admin view") return render_template('poll-react.html', poll=poll, async_mode=socketio.async_mode) elif not poll.is_open: logger.info("Poll not open") return render_template('poll-closed.html', poll=poll) elif user.may_respond(poll): logger.info('User may respond') return render_template('poll-react.html', poll=poll, async_mode=socketio.async_mode) elif not poll.is_results_visible: "User has voted but results not visible" route = '/' + poll.short_code + '/success' else: "User has voted, showing results" route = '/' + short_code + '/results' else: flash('Sorry, that page does not exist.') route = '/' return redirect(route)
def get(self): try: cursor = Cursor.from_websafe_string(self.request.get('cursor')) except BadValueError: cursor = None try: limit = int(self.request.get('limit')) if limit <= 0: raise ValueError except (TypeError, ValueError): limit = 100 query = Poll.query().order(-Poll.created) polls, next_cursor, has_more = query.fetch_page(limit, start_cursor=cursor) for poll in polls: self.response.write(poll.render_html() + '\n\n<hr>\n\n') if not has_more: return more_url = '?cursor={}&limit={}'.format( next_cursor.to_websafe_string(), limit) self.response.write('<p><a href="{}">More</a></p>'.format(more_url))
def handle_inline_query(self): inline_query = self.update.inline_query text = inline_query.query.lower() uid = str(inline_query.from_user.id) query = Poll.query(Poll.admin_uid == uid, Poll.title_short >= text, Poll.title_short < text + u'\ufffd') results = [] polls = sorted(query.fetch(50), key=lambda poll: poll.created, reverse=True) for poll in polls: qr_id = str(poll.key.id()) qr_title = poll.title qr_description = poll.generate_options_summary() content = { 'message_text': poll.render_text(), 'parse_mode': 'HTML' } reply_markup = poll.build_vote_buttons() result = { 'type': 'article', 'id': qr_id, 'title': qr_title, 'description': qr_description, 'input_message_content': content, 'reply_markup': reply_markup, 'thumb_url': self.THUMB_URL } results.append(result) self.answer_inline_query(results)
def edit_poll(short_code): """Edit poll.""" poll = Poll.get_from_code(short_code) if current_user.is_authenticated and current_user.is_admin(poll): return render_template('poll-react.html', poll=poll) else: return redirect('/' + short_code)
def get(self, pid): try: pid = int(pid) poll = Poll.get_by_id(pid) if not poll: raise ValueError except ValueError: self.response.set_status(404) self.response.write('Invalid poll ID') return self.response.write(poll.render_html())
def question_callback(bot: telegram.Update, update: telegram.ext.Dispatcher, args: [str]): args = _reconstruct_args(args) LOGGER.debug("'Question' called with {args}".format(args=args)) if len(args) < 3: update.message.reply_text("Il n'y a pas assez d'arguments:\n\n{}".format(QUESTION_CMD)) return new_poll = Poll.create(question=args[0]) answers = [] for answer in args[1:]: answers.append(Answer.create(poll=new_poll, answer=answer)) show_poll(new_poll, answers, update, bot)
def create_new_poll(): """Process info from new_poll.html form and add to database.""" title = request.form.get('title') prompt = request.form.get('prompt') description = request.form.get('description') poll = Poll(title=title, prompt=prompt, description=description) db.session.add(poll) db.session.commit() return redirect(f'poll/{poll.poll_id}')
def make_poll_categories_and_submit(): """Makes and auto-complete polls if we have all answers but no polls yet.""" unpolled_questions = QuestionModel.query.filter_by(poll_asked=False).join(Answer).all() for q in unpolled_questions: if len(q.answers) >= 4: title = "Poll: %s" % q.title question = "Select all poll answers that apply. %s" % q.question description = q.description keywords = q.keywords poll_price = '0.05' poll_num_ppl_to_ask = 8 answers_to_one_q = q.answers #object ratings = [] for a in answers_to_one_q: ratings.append((a.answer, a.answer_id)) if len(ratings)>=4: # Create a new poll from the data returned in makepoll.py new_poll = Poll(question_id=q.question_id, poll_price=poll_price, poll_num_ppl_to_ask=poll_num_ppl_to_ask) make_p = makepoll.make_poll(title, question, description, keywords, poll_price, ratings) new_poll.poll_amzn_hit_id = make_p[0].HITId is_poll_asked = ( QuestionModel.query .filter_by(question_id=q.question_id) .update({"poll_asked": True}) ) db.session.add(new_poll) db.session.commit()
def show_admin_all_polls(): entries = Poll.get_all().fetch(10) for entry in entries: entry.answers = PollAnswer.query(PollAnswer.parent == entry.key) if entry.type == "poll": entry.yes = PollAnswer.query(PollAnswer.parent == entry.key, PollAnswer.answer == "yes").count() entry.no = PollAnswer.query(PollAnswer.parent == entry.key, PollAnswer.answer == "no").count() config = app.config.get('config') jsonconfig = json.dumps(app.config.get('config')) return render_template('admin/all_polls.html', appconfig=config, config=jsonconfig, entries=entries)
def show_admin_all_polls(): entries = Poll.get_all().fetch(10) for entry in entries: entry.answers = PollAnswer.query(PollAnswer.parent == entry.key) for answer in entry.answers: answer.student = getStudent(answer.studentId) answer.studentName = getStudentName(answer.student) if entry.type == "poll": entry.yes = PollAnswer.query(PollAnswer.parent == entry.key, PollAnswer.answer == "yes").count() entry.no = PollAnswer.query(PollAnswer.parent == entry.key, PollAnswer.answer == "no").count() jsonconfig = json.dumps(app.config.get('config')) return render_template('admin/all_polls.html', jsconfig=jsonconfig, entries=entries)
def update_poll(poll_id): """Update poll data for a poll id""" poll = Poll.query.get(poll_id) data = request.form.to_dict() resp_data = {'poll_id': poll_id} for attr, val in data.iteritems(): if attr == 'short_code' and Poll.get_from_code(val): return 'This short code is already in use.' setattr(poll, attr, val) resp_data[attr] = val poll.updated_at = datetime.now() db.session.add(poll) db.session.commit() return jsonify(resp_data)
def show_results(short_code): poll = Poll.get_from_code(short_code) user = User.get_user() if poll is not None: # Ensure this is a valid poll route if user.is_admin(poll): return render_template('poll-react.html', poll=poll) elif not poll.is_open: return render_template('poll-closed.html', poll=poll) elif not poll.is_results_visible: route = '/' + poll.short_code + '/success' else: return render_template('poll-react.html', poll=poll) else: flash('Sorry, that page does not exist.') route = '/' return redirect(route)
def dashboard(): students = getStudents() for student in students: student['rewardcount'] = Log.get_by_type(student['studentId'], LogType.REWARD).count() entries = Poll.get_todays().fetch(5) for entry in entries: entry.answers = PollAnswer.query(PollAnswer.parent == entry.key) if entry.type == "poll": entry.yes = PollAnswer.query(PollAnswer.parent == entry.key, PollAnswer.answer == "yes").count() entry.no = PollAnswer.query(PollAnswer.parent == entry.key, PollAnswer.answer == "no").count() config = app.config.get('config') jsonconfig = json.dumps(app.config.get('config')) return render_template('admin/dashboard.html', appconfig=config, config=jsonconfig, entries=entries, students=students)
def add_poll_to_db(): """Adds poll form data to database""" # get data from form prompt = request.form.get('prompt') poll_type = int(request.form.get('poll_type')) is_results_visible = bool(request.form.get('is_results_visible')) title = prompt # create and add objects to db if current_user.is_authenticated: user = current_user else: user = User() poll = Poll(poll_type_id=poll_type, title=title, prompt=prompt, is_results_visible=is_results_visible) PollAdmin(poll_id=poll.poll_id, user_id=user.user_id) # TODO: send poll creation email to user # email = request.form.get('email') # if not open-ended, create Response objects if not poll.poll_type.collect_response: # parse responses from form responses = request.form.get('responses') responses = responses.split('\n') for response in responses: response = Response(poll_id=poll.poll_id, user_id=user.user_id, text=response.strip(), weight=responses.index(response) + 1) db.session.add(response) db.session.commit() # only commit once all Responses are added route = '/' + poll.short_code return redirect(route)
def trigger_notification(): header = cgi.escape(request.form['header']) body = cgi.escape(request.form['body']) type = cgi.escape(request.form['type']) poll = Poll() poll.type = type poll.question = header poll.html = body poll_key = poll.put() id = poll_key.id() if type == "poll": p.trigger('polls', 'new_poll', { 'id': id, 'header': header, 'body': body, 'title': header }) elif type == "alert": if not body: p.trigger('polls', 'new_alert', { 'id': id, 'title': 'New Announcement', 'body': header }) else: p.trigger('polls', 'new_alert', { 'id': id, 'title': header, 'body': body }) elif type == "link": p.trigger('polls', 'new_link', { 'id': id, 'header': header, 'link': body }) elif type == "quiz": p.trigger('polls', 'quiz', {'id': id}) else: p.trigger('polls', 'new_survey', { 'id': id, 'header': header, 'body': body }) return redirect("/allpolls")
def sms_show_prompt(short_code): poll = Poll.get_from_code(short_code) phone = request.values['From'] user = User.get_from_phone(phone) resp = MessagingResponse() if ((poll.poll_type.collect_response and Response.get_response(poll=poll, user=user)) or (user in poll.get_users_from_tally() and not poll.poll_type.multi_select)): resp.message('You have already submitted a response.') elif poll.poll_type.collect_response: resp.message(poll.prompt + '\n\nEnter your response.') else: resp.message(poll.prompt + '\n\nEnter # of response option.') session['short_code'] = poll.short_code return str(resp)
class PollTesting(unittest.TestCase): def setUp(self): self.poll = Poll("Do you like our voting system?", ["Yes", "Of course", "absolutely"], True, True, "001") self.json = {'question': 'Do you like our voting system?', 'options': ['Yes', 'Of course', 'absolutely'], 'named': True, 'unique': True, 'creator_user_id': '001'} self.bad_poll_json = {'my_name': 'John'} def test_create_poll(self): self.assertEqual(self.poll.question, "Do you like our voting system?") self.assertEqual(self.poll.options, ["Yes", "Of course", "absolutely"]) self.assertEqual(self.poll.named, True) self.assertEqual(self.poll.unique, True) self.assertEqual(self.poll.creator_user_id, "001") def test_makeJson(self): self.assertDictEqual(self.poll.makeJson(), self.json) def test_getPollFromJson(self): self.assertEqual(getPollFromJson(self.json), self.poll) self.assertRaises(Exception, lambda: getPollFromJson(self.bad_poll_json))
def dashboard(): students = getStudents() meetings = getMeetings() for student in students: student['rewardcount'] = Log.get_by_type(student['studentId'], 'reward').count() entries = Poll.get_todays().fetch(5) for entry in entries: entry.answers = PollAnswer.query(PollAnswer.parent == entry.key) for answer in entry.answers: answer.student = getStudent(answer.studentId) answer.studentName = getStudentName(answer.student) if entry.type == "poll": entry.yes = PollAnswer.query(PollAnswer.parent == entry.key, PollAnswer.answer == "yes").count() entry.no = PollAnswer.query(PollAnswer.parent == entry.key, PollAnswer.answer == "no").count() jsonconfig = json.dumps(app.config.get('config')) return render_template('admin/dashboard.html', jsconfig=jsonconfig, entries=entries, students=students, meetings=meetings)
def handle_message(self): message = self.update.message User.populate_by_id(message.from_user.id, first_name=message.from_user.first_name, last_name=message.from_user.last_name, username=message.from_user.username) if not message.text: return text = message.text uid = str(message.chat.id) responding_to = memcache.get(uid) def deliver_poll(poll): backend.send_message(0.5, chat_id=uid, text=poll.render_text(), parse_mode='HTML', reply_markup=poll.build_admin_buttons()) if text.startswith('/start'): backend.send_message(chat_id=uid, text=self.NEW_POLL) memcache.set(uid, value='START', time=3600) return elif text == '/done' and responding_to and responding_to.startswith( 'OPT '): poll = Poll.get_by_id(int(responding_to[4:])) if not poll.options: backend.send_message(chat_id=uid, text=self.ERROR_PREMATURE_DONE) return backend.send_message(chat_id=uid, text=self.DONE) deliver_poll(poll) elif text == '/polls': header = [util.make_html_bold('Your polls')] recent_polls = Poll.query( Poll.admin_uid == uid).order(-Poll.created).fetch(50) body = [ u'{}. {}'.format(i + 1, poll.generate_poll_summary_with_link()) for i, poll in enumerate(recent_polls) ] footer = ['Use /start to create a new poll.'] output = u'\n\n'.join(header + body + footer) backend.send_message(chat_id=uid, text=output, parse_mode='HTML') elif text.startswith('/view_'): try: poll = Poll.get_by_id(int(text[6:])) if not poll or poll.admin_uid != uid: raise ValueError deliver_poll(poll) except ValueError: backend.send_message(chat_id=uid, text=self.HELP) elif responding_to == 'START': new_poll_key = Poll.new(admin_uid=uid, title=text).put() bold_title = util.make_html_bold_first_line(text) backend.send_message(chat_id=uid, text=self.FIRST_OPTION.format(bold_title), parse_mode='HTML') memcache.set(uid, value='OPT {}'.format(new_poll_key.id()), time=3600) return elif responding_to and responding_to.startswith('OPT '): poll = Poll.get_by_id(int(responding_to[4:])) poll.options.append(Option(text)) poll.put() if len(poll.options) < 10: backend.send_message(chat_id=uid, text=self.NEXT_OPTION) return backend.send_message(chat_id=uid, text=self.DONE) deliver_poll(poll) else: backend.send_message(chat_id=uid, text=self.HELP) memcache.delete(uid)
def success(short_code): """Show success page.""" poll = Poll.get_from_code(short_code) return render_template('success.html')
def handle_callback_query(self): callback_query = self.update.callback_query extract_user_data = lambda user: (user.id, { 'first_name': user.first_name, 'last_name': user.last_name, 'username': user.username }) uid, user_profile = extract_user_data(callback_query.from_user) Respondent.populate_by_id(uid, **user_profile) imid = callback_query.inline_message_id is_admin = not imid chat_id = callback_query.message.chat.id if is_admin else None mid = callback_query.message.message_id if is_admin else None try: params = callback_query.data.split() poll_id = int(params[0]) action = params[1] except (AttributeError, IndexError, ValueError): logging.warning('Invalid callback query data') self.answer_callback_query( 'Invalid data. This attempt will be logged!') return poll = Poll.get_by_id(poll_id) if not poll: backend.api_call('edit_message_reply_markup', inline_message_id=imid, chat_id=chat_id, message_id=mid) self.answer_callback_query('Sorry, this poll has been deleted') return if action.isdigit(): poll, status = Poll.toggle(poll_id, int(action), uid, user_profile) backend.api_call( 'edit_message_text', inline_message_id=imid, chat_id=chat_id, message_id=mid, text=poll.render_text(), parse_mode='HTML', reply_markup=poll.build_vote_buttons(admin=is_admin)) elif action == 'refresh' and is_admin: status = 'Results updated!' backend.api_call('edit_message_text', chat_id=chat_id, message_id=mid, text=poll.render_text(), parse_mode='HTML', reply_markup=poll.build_admin_buttons()) elif action == 'vote' and is_admin: status = 'You may now vote!' backend.api_call('edit_message_reply_markup', chat_id=chat_id, message_id=mid, reply_markup=poll.build_vote_buttons(admin=True)) elif action == 'delete' and is_admin: poll.key.delete() status = 'Poll deleted!' backend.api_call('edit_message_reply_markup', chat_id=chat_id, message_id=mid) elif action == 'back' and is_admin: status = '' backend.api_call('edit_message_reply_markup', chat_id=chat_id, message_id=mid, reply_markup=poll.build_admin_buttons()) else: status = 'Invalid data. This attempt will be logged!' logging.warning('Invalid callback query data') self.answer_callback_query(status)
def sms_add_input(short_code): poll = Poll.get_from_code(short_code) resp = MessagingResponse() sms = request.values['Body'] phone = request.values['From'] user = User.get_from_phone(phone) # Handle responses if poll.poll_type.collect_response: weight = Response.query.filter( Response.poll_id == poll.poll_id).count() response = Response(poll_id=poll.poll_id, user_id=user.user_id, text=sms, weight=weight) db.session.add(response) db.session.commit() resp.message('Your response "{}" has been recorded.'.format( response.text)) del session['short_code'] # Handle tallys else: # Check that sms is a number try: index = int(sms) responses = poll.responses try: response = responses[index - 1] # Check that response option exists if response: # Check that user hasn't already responded if Tally.query.filter( Tally.response_id == response.response_id, Tally.user_id == user.user_id).first(): resp.message( 'You have already responsed for "{}".'.format( response.text)) # Add tally else: tally = Tally(response_id=response.response_id, user_id=user.user_id) db.session.add(tally) db.session.commit() # emit_new_result(response) emit_response_update(response) resp.message( 'Your response "{}" has been recorded.'.format( response.text)) if poll.poll_type.multi_select: resp.message('Continue responding? Y/N') return str(resp) # redirect for route for Y/N del session['short_code'] except: resp.message( 'Sorry that response does not exist. Please enter another number.' ) except: resp.message( 'Sorry, please enter your response option as a number.') return str(resp)
def setUp(self): self.poll = Poll("Do you like our voting system?", ["Yes", "Of course", "absolutely"], True, True, "001") self.json = {'question': 'Do you like our voting system?', 'options': ['Yes', 'Of course', 'absolutely'], 'named': True, 'unique': True, 'creator_user_id': '001'} self.bad_poll_json = {'my_name': 'John'}
def getAllPolls(self, opt_user): polls = Poll.query().fetch() pollsJsons = map(lambda poll: self.pollToJson(poll, opt_user), polls) self.response.out.write(json.dumps(pollsJsons))
def getMostRecentPoll(self, opt_user): mostRecentPoll = Poll.query().order(-Poll.publishedOn).get() self.response.out.write( json.dumps(self.pollToJson(mostRecentPoll, opt_user)))
def test_data(): """Create sample data for testing.""" # Create users anon_user = User() anon_admin = User() admin = User( fname='Karynn', lname='Ikeda', email='admin', password_hash= 'pbkdf2:sha1:1000$rOEh4Opu$117c2a9fdaca6bf2a927e5097ca7f8ce6da32307') user = User( fname='John', lname='Doe', email='*****@*****.**', password_hash= 'pbkdf2:sha1:1000$jZyba5B5$c7da27f064ae8ec0c93d1f2e1789e9e3e19b49a3') user_responded = User( fname='Carly', lname='Banks', email='*****@*****.**', phone='+14153334444', password_hash= 'pbkdf2:sha1:1000$83T7iOeT$8154ddce2cd25af9688622aac45cb2054827a212') anon_user_responded = User(session_id='session') db.session.add_all( [anon_user, anon_admin, admin, user, anon_user_responded]) db.session.commit() # Create polls mc_poll = Poll(poll_type_id=1, title='Colors - Multiple Choice', prompt='What is your favorite color?', short_code='multi', admin_code='adminmc', latitude=37.7888197, longitude=-122.4116021) sa_poll = Poll(poll_type_id=2, title='Colors - Select All', prompt='What is your favorite color?', short_code='all', admin_code='adminsa', is_results_visible=False) oe_poll = Poll(poll_type_id=3, title='Colors - Open-Ended', prompt='What is your favorite color?', short_code='open', admin_code='adminoe') ro_poll = Poll(poll_type_id=5, title='Colors - Ranked Order', prompt='Rank the colors from most to lease favorite.', short_code='ranked', admin_code='adminro') q_poll = Poll(poll_type_id=4, title='Questions', prompt='Ask me anything.', short_code='questions', admin_code='adminq') closed_poll = Poll(poll_type_id=3, title='Closed', prompt='What is your favorite color?', short_code='close', admin_code='adminclosed', is_open=False) db.session.add_all( [mc_poll, sa_poll, oe_poll, ro_poll, q_poll, closed_poll]) db.session.commit() # Create PollAdmin mc_admin = PollAdmin(poll_id=mc_poll.poll_id, user_id=admin.user_id) sa_admin = PollAdmin(poll_id=sa_poll.poll_id, user_id=admin.user_id) oe_admin = PollAdmin(poll_id=oe_poll.poll_id, user_id=admin.user_id) ro_admin = PollAdmin(poll_id=ro_poll.poll_id, user_id=admin.user_id) q_admin = PollAdmin(poll_id=q_poll.poll_id, user_id=admin.user_id) closed_admin = PollAdmin(poll_id=closed_poll.poll_id, user_id=admin.user_id) mc_anon_admin = PollAdmin(poll_id=mc_poll.poll_id, user_id=anon_admin.user_id) sa_anon_admin = PollAdmin(poll_id=sa_poll.poll_id, user_id=anon_admin.user_id) oe_anon_admin = PollAdmin(poll_id=oe_poll.poll_id, user_id=anon_admin.user_id) db.session.add_all([ mc_admin, sa_admin, oe_admin, q_admin, closed_admin, mc_anon_admin, sa_anon_admin, oe_anon_admin ]) db.session.commit # Create responses mc_r1 = Response(poll_id=mc_poll.poll_id, user_id=admin.user_id, text='Red', weight=1) mc_r2 = Response(poll_id=mc_poll.poll_id, user_id=admin.user_id, text='Blue', weight=2) mc_r3 = Response(poll_id=mc_poll.poll_id, user_id=admin.user_id, text='Yellow', weight=3) sa_r1 = Response(poll_id=sa_poll.poll_id, user_id=admin.user_id, text='Cyan', weight=1) sa_r2 = Response(poll_id=sa_poll.poll_id, user_id=admin.user_id, text='Magenta', weight=2) sa_r3 = Response(poll_id=sa_poll.poll_id, user_id=admin.user_id, text='Yellow', weight=3) oe_r1 = Response(poll_id=oe_poll.poll_id, user_id=user_responded.user_id, text='Red', weight=1) oe_r2 = Response(poll_id=oe_poll.poll_id, user_id=anon_user_responded.user_id, text='Blue', weight=1) ro_r1 = Response(poll_id=ro_poll.poll_id, user_id=admin.user_id, text='Purple', weight=1) ro_r2 = Response(poll_id=ro_poll.poll_id, user_id=admin.user_id, text='Green', weight=2) ro_r3 = Response(poll_id=ro_poll.poll_id, user_id=admin.user_id, text='Orange', weight=3) q_r1 = Response(poll_id=q_poll.poll_id, user_id=user_responded.user_id, text='What is your name?', weight=1) q_r2 = Response(poll_id=q_poll.poll_id, user_id=anon_user_responded.user_id, text='Where do you live?', weight=1) q_r3 = Response(poll_id=q_poll.poll_id, user_id=user_responded.user_id, text='How old are you?', weight=1) db.session.add_all([ mc_r1, mc_r2, mc_r3, sa_r1, sa_r2, sa_r3, ro_r1, ro_r2, ro_r3, oe_r1, oe_r2, q_r1, q_r2, q_r3 ]) db.session.commit() # Create Tallys mc_r1_t1 = Tally(response_id=mc_r1.response_id, user_id=user_responded.user_id) mc_r1_t2 = Tally(response_id=mc_r1.response_id, user_id=anon_user_responded.user_id) sa_r1_t1 = Tally(response_id=sa_r1.response_id, user_id=user_responded.user_id) sa_r1_t2 = Tally(response_id=sa_r1.response_id, user_id=anon_user_responded.user_id) sa_r2_t1 = Tally(response_id=sa_r2.response_id, user_id=anon_user_responded.user_id) sa_r3_t1 = Tally(response_id=sa_r3.response_id, user_id=user_responded.user_id) q_r1_t1 = Tally(response_id=q_r1.response_id, user_id=user_responded.user_id) q_r1_t2 = Tally(response_id=q_r1.response_id, user_id=anon_user_responded.user_id) q_r2_t1 = Tally(response_id=q_r2.response_id, user_id=anon_user_responded.user_id) q_r3_t1 = Tally(response_id=q_r3.response_id, user_id=user_responded.user_id) db.session.add_all([ mc_r1_t1, mc_r1_t2, sa_r1_t1, sa_r1_t2, sa_r2_t1, sa_r3_t1, q_r1_t1, q_r1_t2, q_r2_t1, q_r3_t1 ]) db.session.commit()