def info_test_survey(hashed_user_id, hashed_treatment): user_id = '10' + hashed_user_id[12] + hashed_user_id[3] treatment = hashed_treatment[7] # record info page as read by user db = get_db() now = datetime.now() db.execute( 'INSERT INTO survey (user_id, day, result, created, question_id)' ' VALUES (?, ?, ?, ?, ?)', (user_id, 10, "read", now, "readInfo")) db.commit() if request.method == 'POST': questions = [ 'eventName', 'eventNameOrder', 'airQuality', 'source', 'sourceOrder' ] now = datetime.now() db = get_db() for question in questions: answer = request.form[question] db.execute( 'INSERT INTO survey (user_id, day, result, created, question_id)' ' VALUES (?, ?, ?, ?, ?)', (user_id, 10, answer, now, question)) db.commit() return render_template('pilot/completionPage.html') return render_template('pilot/surveyInfo.html')
def test_get_close_db(app): with app.app_context(): db = get_db() assert db is get_db() with pytest.raises(sqlite3.ProgrammingError) as e: db.execute('SELECT 1') assert 'closed' in str(e)
def update_wechatID(): db = get_db() output_message = '' if request.method == 'POST': user_id = request.form['user_id'] wechat_id = request.form['wechat_id'] cohort = request.form['cohort'] user = db.execute( 'SELECT user_id, day, treatment, cohort' ' FROM user u' ' WHERE u.user_id = ? AND u.cohort = ?', ( user_id, cohort, )).fetchone() if user is None: db.execute( 'INSERT INTO user (user_id, day, wechat_id, cohort, treatment, user_id_hashid, day_hashid)' ' VALUES (?, ?, ?, ?, ?, ?, ?)', (user_id, 99, wechat_id, cohort, 'treatment', 'user_id_hashid', 'day_hashid')) db.commit() output_message = 'Done:) <b>Inserted</b> user with user_id %s, wechat_id %s, cohort %s' % ( user_id, wechat_id, cohort) else: db.execute( 'UPDATE user SET wechat_id=?, cohort = ? WHERE user_id = ?', (wechat_id, cohort, user_id)) db.commit() output_message = 'Done:) <b>Updated</b> user with user_id %s, wechat_id %s, cohort %s' % ( user_id, wechat_id, cohort) return render_template('crud/updateWechatID.html', output_message=output_message)
def user_results(): """Show all the surveys, and all results.""" db = get_db() surveys = db.execute('SELECT user_id, day, question_id, result, created' ' FROM survey s' ' ORDER BY created ASC').fetchall() return render_template('crud/surveyList.html', surveys=surveys)
def get_latest_checkpoint_answers(user_id, day): db = get_db() answers = db.execute( 'SELECT question_id, result' ' FROM survey s' ' WHERE s.user_id = ? AND s.day = ?' ' ORDER BY s.created DESC', ( user_id, day, )).fetchall() if answers: latest_answers = {} for answer in answers: question = answer['question_id'] result = answer['result'] if question == 'correctAnswerAtCheckpoints': break if question == 'checkAQSource': if question in latest_answers.keys(): latest_answers[question].add(result) else: latest_answers[question] = {result} else: latest_answers[question] = result return latest_answers return None
def get_lastpage(user_id, day, day_to_lastpage_dict={ 1: 7, 2: 6, 3: 4, 4: 2, 5: 2, 6: 11, 7: 5, 8: 3 }): # excluding the info & final page db = get_db() last_activity = db.execute( 'SELECT survey_page, day' ' FROM activity a' ' WHERE a.user_id = ?', (user_id, )).fetchone() if last_activity is None: lastpage = 0 else: lastday = last_activity[1] if day < lastday: # completed lastpage = day_to_lastpage_dict[day] elif day == lastday: # partially completed lastpage = last_activity[0] else: lastpage = 0 return lastpage
def app(): db_fd, db_path = tempfile.mkstemp() app = create_app({ 'TESTING': True, 'DATABASE': db_path, }) with app.app_context(): init_db() get_db().executescript(_data_sql) yield app os.close(db_fd) os.unlink(db_path)
def users(): """Show all the surveys, and all results.""" db = get_db() users = db.execute( 'SELECT user_id, day, wechat_id, treatment, cohort, user_id_hashid, day_hashid' ' FROM user s' ' ORDER BY user_id ASC').fetchall() return render_template('crud/userList.html', users=users)
def get_activity_day(user_id): db = get_db() activity_day = db.execute( 'SELECT user_id, day' ' FROM activity a' ' WHERE a.user_id = ?', (user_id, )).fetchone() day = activity_day[1] return day
def activity_insert(user_id): now = datetime.now() db = get_db() db.execute( 'INSERT INTO activity (user_id, day, day_complete, survey_page, day_started, curr_time)' ' VALUES (?, ?, ?, ?, ?, ?)', (user_id, 1, False, 0, now, now)) db.commit() return 'complete'
def delete_event(event_id, cohort): db = get_db() db.execute('DELETE FROM infos WHERE event_id = ? AND cohort = ?', ( event_id, cohort, )) db.commit() return 'complete'
def user_activities(): """Show all the surveys, and all results.""" db = get_db() users = db.execute( 'SELECT user_id, day, day_complete, survey_page, day_started, curr_time' ' FROM activity s' ' ORDER BY user_id ASC').fetchall() return render_template('crud/activityList.html', users=users)
def all_pages(): """Show all the surveys, and all results.""" db = get_db() pages = db.execute( 'SELECT day, page, question_name, cohort' ' FROM pages p' ' ORDER BY cohort ASC, day ASC, page ASC, question_name ASC').fetchall( ) return render_template('crud/pageList.html', pages=pages)
def get_event_info(event_id, cohort=5): info = get_db().execute( 'SELECT i.event_id,title,subtitle,info_date,info_time,location,image_file,short_description,low_temp,high_temp,suitable_for_family,suitable_for_friends,suitable_for_lover,suitable_for_baby,suitable_for_elderly,suitable_for_pet,event_details,phrase_for_week, phrase_for_day, phrase_for_header' ' FROM infos i' ' WHERE i.event_id = ? AND cohort = ?', ( event_id, cohort, )).fetchone() return info
def user_insert(user_id, day, wechat_id, cohort, treatment, user_id_hashid, day_hashid): db = get_db() db.execute( 'INSERT INTO user (user_id, day, wechat_id, cohort, treatment, user_id_hashid, day_hashid)' ' VALUES (?, ?, ?, ?, ?, ?, ?)', (user_id, day, wechat_id, cohort, treatment, user_id_hashid, day_hashid)) db.commit() return 'complete'
def activity_update(user_id, day, day_complete, survey_page, h1, h2): now = datetime.now() db = get_db() db.execute( 'REPLACE INTO activity (user_id, day, day_complete, survey_page, day_started, curr_time)' ' VALUES (?, ?, ?, ?, ?, ?)', (user_id, day, day_complete, survey_page, now - timedelta(hours=int(h1)), now - timedelta(hours=int(h2)))) db.commit() return 'complete'
def update_werun(surveyor_id): db = get_db() # query pledged steps users = db.execute( 'SELECT DISTINCT u.user_id, u.wechat_id, s.result' ' FROM user u' ' LEFT JOIN survey s ON u.user_id = s.user_id ' ' WHERE u.cohort = ? AND s.day = ? AND s.question_id = ?' ' ORDER BY u.user_id ASC', ( 5, 7, 'walkathonSteps', )).fetchall() # select users based on surveyor_id relevent_users = [] for user in users: if int(user['user_id'] / 1e6) % 10 == surveyor_id: relevent_users.append(user) # save actual steps in werun table # question names are set to: {{ user['user_id'] }}-installed and {{ user['user_id'] }}-name if request.method == 'POST': form = request.form now = datetime.now() db = get_db() for user in relevent_users: user_id = user['user_id'] steps = form[str(user_id) + '-steps'] if steps != '': db.execute( 'INSERT INTO werun (user_id, steps, installed)' ' VALUES (?, ?, ?)', ( user_id, int(steps), form[str(user_id) + '-installed'], )) db.commit() return render_template('crud/updateWerun.html', users=relevent_users)
def get_user(user_id_hashid, day_hashid, cohort=5): user = get_db().execute( 'SELECT user_id, day, treatment' ' FROM user u' ' WHERE u.user_id_hashid = ? AND u.day_hashid = ? AND u.cohort = ?', ( user_id_hashid, day_hashid, cohort, )).fetchone() if user is None: # abort(404, "User {0}/{1}/{2} doesn't exist.".format(user_id_hashid, day_hashid, cohort)) user = get_db().execute( 'SELECT user_id, day, treatment' ' FROM user u' ' WHERE u.user_id_hashid = ? AND u.day_hashid = ? AND u.cohort = ?', ( user_id_hashid, day_hashid, 4, )).fetchone() return user
def update_lastpage(lastpage, day_complete, user_id, day): now = datetime.now() db = get_db() db.execute( 'UPDATE activity SET survey_page = ?, curr_time = ?, day_complete = ? WHERE user_id = ? AND day = ?', ( lastpage, now, day_complete, user_id, day, )) db.commit()
def get_werun(): users = get_db().execute( 'SELECT DISTINCT u.user_id, u.wechat_id, s.result, w.installed, w.steps' ' FROM user u' ' LEFT JOIN survey s ON u.user_id = s.user_id ' ' LEFT JOIN werun w ON u.user_id = w.user_id ' ' WHERE u.cohort = ? AND s.day = ? AND s.question_id = ?' ' ORDER BY u.user_id ASC', ( 5, 7, 'walkathonSteps', )).fetchall() return render_template('crud/werun.html', users=users)
def info_test(hashed_user_id, hashed_treatment): user_id = '10' + hashed_user_id[12] + hashed_user_id[3] treatment = hashed_treatment[7] # check if user already read the info page read = get_db().execute( 'SELECT result' ' FROM survey s' ' WHERE s.user_id = ? AND s.day = ? AND s.question_id = ?', (user_id, 10, "readInfo")).fetchone() # not read yet if read is None: # get test info and sources info = get_db().execute( 'SELECT i.event_id,title,subtitle,info_date,info_time,location,image_file,short_description,low_temp,high_temp,suitable_for_family,suitable_for_friends,suitable_for_lover,suitable_for_baby,suitable_for_elderly,suitable_for_pet,event_details,phrase_for_week, phrase_for_day, phrase_for_header' ' FROM infos i' ' WHERE i.event_id = ? AND cohort = ?', ( 9, 1, )).fetchone() curr_air_quality_source = u'(来自:北京晚报)' curr_air_quality_source_logo = 'img/SourceBJEN.png' return render_template( 'ui_test/infoPage' + treatment + '.html', hashed_user_id=hashed_user_id, hashed_treatment=hashed_treatment, info=info, air_quality_source=curr_air_quality_source, air_quality_source_logo=curr_air_quality_source_logo) # read info already, skip to survey else: return redirect( url_for('ui_test.info_test_survey', hashed_user_id=hashed_user_id, hashed_treatment=hashed_treatment))
def update_events(): info = None if request.method == 'POST': # search for event_id and cohort event_id = request.form['event_id'] cohort = request.form['cohort'] db = get_db() info = db.execute( 'SELECT * FROM infos i WHERE i.event_id = ? AND cohort = ?', ( event_id, cohort, )).fetchone() # not in db if info is None: db.execute('INSERT INTO infos (event_id, cohort) VALUES (?, ?)', (event_id, cohort)) info = db.execute( 'SELECT * FROM infos i WHERE i.event_id = ? AND cohort = ?', ( event_id, cohort, )).fetchone() db.commit() flash( 'event_id %s and cohort %s combination not found, fill-in the rest to insert into db.' % (event_id, cohort)) f = request.form db = get_db() for field in f.keys(): for value in f.getlist(field): db.execute( 'UPDATE infos SET ' + field + ' = ? WHERE event_id = ? AND cohort = ?', (value, event_id, cohort)) db.commit() return render_template('crud/updateEvent.html', info=info)
def get_last_question(user_id): db = get_db() last_question_query = db.execute( 'SELECT question_id, day' ' FROM survey s' ' WHERE s.user_id = ?' ' ORDER BY s.created DESC LIMIT 1', (user_id, )).fetchone() if last_question_query: last_question = { 'last_question_name': last_question_query[0], 'last_question_day': last_question_query[1] } else: last_question = None return last_question
def get_page_from_question_name(day, question_name, cohort=5): db = get_db() page_query = db.execute( 'SELECT page' ' FROM pages p' ' WHERE p.day = ? AND p.cohort = ? AND p.question_name = ?', ( day, cohort, question_name, )).fetchone() if page_query: page = page_query[0] else: page = 0 return page
def get_lastpage(user_id, day, day_to_lastpage_dict={1: 4, 2: 9}): db = get_db() last_activity = db.execute( 'SELECT survey_page, day' ' FROM activity a' ' WHERE a.user_id = ?', (user_id, )).fetchone() if last_activity is None: lastpage = 0 else: lastday = last_activity[1] if day < lastday: # completed lastpage = day_to_lastpage_dict[day] elif day == lastday: # partially completed lastpage = last_activity[0] else: lastpage = 0 return lastpage
def update_page(action, day, page, question_name, cohort): db = get_db() if action == 'delete': db.execute( 'DELETE FROM pages WHERE day = ? AND page = ? AND question_name = ? AND cohort = ?', ( day, page, question_name, cohort, )) db.commit() elif action == 'insert': db.execute( 'INSERT INTO pages (day, page, question_name, cohort) VALUES (?, ?, ?, ?)', ( day, page, question_name, cohort, )) db.commit() return "Success: {} day {}, page {}, question {}, cohort {}".format( action, day, page, question_name, cohort)
def new_user_process(input_ID, surveyorNumber): db = get_db() users = get_users() cohort_users = users.loc[users.cohort == int(cohort)].drop_duplicates( subset=['user_id']) cohort_users['surveyor'] = ( (pd.to_numeric(cohort_users['user_id']) / 1e6) % 10).astype(int) curr_cohort_user_count = int(len(set(cohort_users['user_id']))) curr_cohort_user_count_mine = int( len( set(cohort_users.loc[cohort_users.surveyor == int( surveyorNumber)]['user_id']))) if (' ' in str(input_ID)): # Prevent inputting space in the input ID return ['<b><font color="red">无效微信号,请核对后再输入一次!</font></b>'] elif input_ID in list( set(users.loc[users.cohort != int(cohort)]['wechat_id']) ): # Already existing user from prev. cohorts return [u'<b><font color="red">该用户已存在</font></b>!', msg_ineligible] elif input_ID in list(set(cohort_users['wechat_id']) ): # Already existing user in current cohort if (int(cohort_users.loc[cohort_users.wechat_id == input_ID]. iloc[0]['surveyor']) != int(surveyorNumber)): return [ u'<font color="red">(其他研究员已输入过该微信号!请不要发送任何信息,并将此用户告知 Zixin 子鑫)<br></font>' ] else: theUser = cohort_users.loc[(cohort_users.wechat_id == input_ID) & (cohort_users.day == 0)] msg_URL = URL + "shanghai/" + theUser.user_id_hashid.iloc[ 0] + "/" + theUser.day_hashid.iloc[0] + "/info" return [ u'<b><font color="red">(您已输入过该微信号!)<br></font>请将其备注名改为</b>:\ <span style="background-color:PaleGreen;">' + str(theUser.user_id.iloc[0]), msg_initial + msg_URL + '<br><br><b>🔺copy above (do not forget URL)</b><span>' ] elif curr_cohort_user_count_mine >= maxnum_cohort_each: # Surveyor's quota is filled if curr_cohort_user_count >= maxnum_cohort: # Cohort mix size reached db.execute( 'INSERT INTO user (user_id, day, wechat_id, cohort, treatment, user_id_hashid, day_hashid)' ' VALUES (?, ?, ?, ?, ?, ?, ?)', ('WAITLIST', 'TBD', str(input_ID), str(int(cohort) + 1), 'TBD', 'TBD', 'TBD')) db.commit() return [ u'<font color="red">人数上限已满:已存入候补名单</font>', msg_maxnum_cohort ] else: return [ u'<font color="red">你的招募人数上限已经达到(棒),但是其他调查者还没有完成。请联系子鑫,请其他调查者招募此用户!</font>' ] else: # Create nickname # if len(cohort_users) == 0: previousMax = 0 else: previousMax = int( (max(pd.to_numeric(cohort_users['user_id']) % 1e6)) / 1e3) nextUserID = int( int(cohort) * 1e7 + int(surveyorNumber) * 1e6 + (previousMax + 1) * 1e3 + randint(1, 999)) # Assign treatment group # treatment = seq_str[seq[previousMax]] # Save user profile in allUsers # for day in range(maxday + 1): user_id_hashids = Hashids(salt=str(10 * nextUserID + day) + "user_id", min_length=16) day_hashids = Hashids(salt=str(10 * nextUserID + day) + "day", min_length=10) hashed_user_id = user_id_hashids.encrypt(nextUserID) hashed_day = day_hashids.encrypt(day) db.execute( 'INSERT INTO user (user_id, day, wechat_id, cohort, treatment, user_id_hashid, day_hashid)' ' VALUES (?, ?, ?, ?, ?, ?, ?)', (str(nextUserID), str(day), str(input_ID), str(cohort), str(treatment), hashed_user_id, hashed_day)) db.commit() if day == 0: msg_URL = URL + "shanghai/" + hashed_user_id + "/" + hashed_day + "/info" # Set up initial allActivities # now = datetime.now() db.execute( 'REPLACE INTO activity (user_id, day, day_complete, survey_page, day_started, curr_time)' ' VALUES (?, ?, ?, ?, ?, ?)', (str(nextUserID), 0, 0, 0, now, now)) db.commit() # Return output for surveyors # return [ u'<b>请将其备注名改为</b>:' + '<span style="background-color:PaleGreen;">' + str(nextUserID), msg_initial + msg_URL + '<br><br><b>🔺copy above (do not forget URL)</b><span>' ]
def get_info(user_id_hashid, day_hashid): user = get_user(user_id_hashid, day_hashid) user_id = user[0] day = user[1] treatment = user[2] user = { 'treatment': treatment, 'day': day, 'user_id_hashid': user_id_hashid, 'day_hashid': day_hashid } # show survey not available on day 99 if get_activity_day(user_id) == 99: return u'抱歉,此调查已过时效。' # consent form on day 0 if day == 0: db = get_db() day1 = db.execute( 'SELECT user_id_hashid, day_hashid' ' FROM user u' ' WHERE u.user_id = ? AND u.day = ?', ( user_id, 1, )).fetchone() day1_user_id_hashid = day1[0] day1_day_hashid = day1[1] if get_activity_day(user_id) > 0: return redirect( url_for('shanghai.get_info', user_id_hashid=day1_user_id_hashid, day_hashid=day1_day_hashid)) if request.method == 'POST': now = datetime.now() consent = request.form['consent'] db.execute( 'INSERT INTO survey (user_id, day, result, created, question_id)' ' VALUES (?, ?, ?, ?, ?)', (user_id, 0, consent, now, 'consent')) db.commit() # redirect to day 1 info page if consented if consent == 'proceed': db.execute( 'UPDATE activity SET day=?, day_complete = ?, curr_time = ? WHERE user_id = ?', (1, 0, now, user_id)) db.commit() return redirect( url_for('shanghai.get_info', user_id_hashid=day1_user_id_hashid, day_hashid=day1_day_hashid)) # show alert box if not to proceed elif consent == 'notProceed': flash(u'如果您不想参与此次调研,只需关闭窗口并删除此联系人即可。如果误点“我不同意”,请点击“我同意参与”。') return render_template('shanghai/consentForm.html') # only show AQ to T2-1/2-2/3 on day 6 if day == 6 and treatment not in ['T0', 'T1']: template = 'AQ' else: template = '' # direct to survey for day 7, 8 (no info) if day > 6: return redirect( url_for('shanghai.get_survey', user_id_hashid=user_id_hashid, day_hashid=day_hashid)) # get event details if on day 1-6 (cohort set to 5) day_to_info_id_dict = {1: 20, 2: 21, 3: 22, 4: 23, 5: 24, 6: 25} info = get_event_info(day_to_info_id_dict[day]) # air quality source for treatment groups different on day 6 treatment_to_aq_source_dict = { 'T0': '', 'T1': '', 'T2-1': u'(来自:上海市环境监测中心)', 'T2-2': u'(来自:上海广播电视台-STV新闻坊)', 'T3': u'(来自:上海发布)' } treatment_to_aq_source_logo_dict = { 'T0': 'img/transparent.png', 'T1': 'img/transparent.png', 'T2-1': 'img/SourceSHEnvironmentLogo.jpg', 'T2-2': 'img/SourceSTVLogo.png', 'T3': 'img/SourceSHRLogo.jpg' } air_quality_source = treatment_to_aq_source_dict[treatment] air_quality_source_logo = treatment_to_aq_source_logo_dict[treatment] air_quality = { 'air_quality_source': air_quality_source, 'air_quality_source_logo': air_quality_source_logo } # if competed direct to last saved survey page (skip info) lastpage = get_lastpage(user_id, day) if lastpage > 0: # have seen the survey page return redirect( url_for('shanghai.get_survey', user_id_hashid=user_id_hashid, day_hashid=day_hashid)) # save show more info timestamp if request.method == 'POST': form = request.form now = datetime.now() db = get_db() # save answer for question in form.keys(): for result in form.getlist(question): db.execute( 'INSERT INTO survey (user_id, day, result, created, question_id)' ' VALUES (?, ?, ?, ?, ?)', (user_id, day, result, now, question)) db.commit() return redirect( url_for('shanghai.get_survey', user_id_hashid=user_id_hashid, day_hashid=day_hashid)) return render_template('shanghai/infoPage' + template + '.html', info=info, user=user, air_quality=air_quality)
def all_events(): """Show all the events.""" db = get_db() events = db.execute('SELECT * FROM infos ORDER BY info_id ASC').fetchall() return render_template('crud/infoList.html', events=events)
def get_survey(user_id_hashid, day_hashid, jrti=None): user = get_user(user_id_hashid, day_hashid) user_id = user[0] day = user[1] treatment = user[2] user = { 'treatment': treatment, 'user_id_hashid': user_id_hashid, 'day_hashid': day_hashid } second_event = get_event_info(26, 5) walkathon = get_event_info(20, 5) t0_air_quality_source = { 'second_event': { 'air_quality_source': u'', 'air_quality_source_logo': 'img/transparent.png' }, 'walkathon': { 'air_quality_source': u'', 'air_quality_source_logo': 'img/transparent.png' } } t1_air_quality_source = { 'second_event': { 'air_quality_source': u'', 'air_quality_source_logo': 'img/transparent.png' }, 'walkathon': { 'air_quality_source': u'(来自:上海市环境监测中心)', 'air_quality_source_logo': 'img/SourceSHEnvironmentLogo.jpg' } } t2_1_air_quality_source = { 'second_event': { 'air_quality_source': u'(来自:上海市环境监测中心)', 'air_quality_source_logo': 'img/SourceSHEnvironmentLogo.jpg' }, 'walkathon': { 'air_quality_source': u'(来自:上海市环境监测中心)', 'air_quality_source_logo': 'img/SourceSHEnvironmentLogo.jpg' } } t2_2_air_quality_source = { 'second_event': { 'air_quality_source': u'(来自:上海广播电视台-STV新闻坊)', 'air_quality_source_logo': 'img/SourceSTVLogo.png' }, 'walkathon': { 'air_quality_source': u'(来自:上海广播电视台-STV新闻坊)', 'air_quality_source_logo': 'img/SourceSTVLogo.png' } } t3_air_quality_source = { 'second_event': { 'air_quality_source': u'(来自:上海广播电视台-STV新闻坊)', 'air_quality_source_logo': 'img/SourceSTVLogo.png' }, 'walkathon': { 'air_quality_source': u'(来自:上海市环境监测中心)', 'air_quality_source_logo': 'img/SourceSHEnvironmentLogo.jpg' } } treatment_to_air_quality_dict = { 'T0': t0_air_quality_source, 'T1': t1_air_quality_source, 'T2-1': t2_1_air_quality_source, 'T2-2': t2_2_air_quality_source, 'T3': t3_air_quality_source, 'T2': t3_air_quality_source, 'T4': t3_air_quality_source } air_quality = treatment_to_air_quality_dict[treatment] # show survey not available on day 99 if get_activity_day(user_id) == 99: return u'抱歉,此调查已过时效。' # mark info page as read last_question = get_last_question(user_id) if not last_question or last_question['last_question_day'] < day: lastpage = 0 else: lastpage = get_page_from_question_name( day, last_question['last_question_name']) # update last page, activity (for day completion) current_page = lastpage + 1 update_lastpage(current_page, 0, user_id, day) day_to_lastpage_dict = {1: 8, 2: 7, 3: 5, 4: 3, 5: 3, 6: 12, 7: 6, 8: 4} if current_page == day_to_lastpage_dict[day]: update_lastpage(current_page, 1, user_id, day) # mark as completed # go to next page on valid submit if jrti: lastpage = jrti if request.method == 'POST': form = request.form now = datetime.now() db = get_db() # save answer for question in form.keys(): for result in form.getlist(question): db.execute( 'INSERT INTO survey (user_id, day, result, created, question_id)' ' VALUES (?, ?, ?, ?, ?)', (user_id, day, result, now, question)) db.commit() # check answer and redirect if needed if (day in [2, 3, 4, 5] and current_page == 1) or (day == 6 and current_page == 3): all_correct = check_result(user_id, day, treatment) timestamp = now if not all_correct: update_lastpage(0, 0, user_id, day) timestamp = now + timedelta(microseconds=100) # save result in survey table as True (correct) / False (incorrect & redirect) to 'correctAnswerAtCheckpoints' # add timedelta to ensure it's the last answer inserted in the survey table db.execute( 'INSERT INTO survey (user_id, day, result, created, question_id)' ' VALUES (?, ?, ?, ?, ?)', (user_id, day, str(all_correct), timestamp, 'correctAnswerAtCheckpoints')) db.commit() return redirect( url_for('shanghai.redirect_at_checkpoint', user_id_hashid=user_id_hashid, day_hashid=day_hashid, all_correct=all_correct)) return redirect( url_for('shanghai.get_survey', user_id_hashid=user_id_hashid, day_hashid=day_hashid, jrti=current_page)) return render_template('shanghai/survey' + str(day) + '.html', user=user, lastpage=lastpage, second_event=second_event, walkathon=walkathon, air_quality=air_quality)