def new(): error = None name = '' key = '' def form(): context = {'error':error,'name':name,'key':key} response = make_response(render_template("survey/new.html",**context)) return response if request.method == 'POST': if not 'name' in request.form or not request.form['name'].strip(): error = 'You need to supply a name for your survey...' return form() name = request.form['name'] if Survey.collection.find({'user':request.user,'name':name}).count(): error = 'You already have a survey with that name...' return form() if 'key' in request.form and request.form['key'].strip(): key = request.form['key'] if re.search(r"[^\w\d\-]+",key): error = "Error: Please use only letters and hyphens for the survey key." return form() else: key = uuid.uuid4().hex if Survey.collection.find({'key':key}).count(): error = 'A survey with this key already exists...' return form() survey = Survey(fields = {},authorized_keys = [],authorized_keys_only = False,key = key,name = name,user = request.user) survey.save() return redirect(url_for("details",survey_key = survey['key'])) else: return form()
def gender(request, group=None): logger.info("view %s, group %s" % (str(stack()[0][3]), group)) if not request.session : # if it doesn't have a session -> start again return render_to_response('start.html', {'error_message': "Your session had time out. Start again.", }, context_instance=RequestContext(request)) logger.info('<gender> sid: {} , POST:{}'.format(request.session.session_key, request.POST)) if 'survey_id' in request.session: del request.session['survey_id'] if request.POST['answer'] == 'Skip survey': request.session['type'] = 'skip' # return render_to_response('index.html', {}, context_instance=RequestContext(request)) return HttpResponseRedirect(reverse('openday.views.app', kwargs={'group':group})) # create new survey s = Survey() s.survey_date = datetime.datetime.now() try: s.group = get_group(group) except: return redirect(reverse('start_view', args=['main'])) s.save() request.session['survey_id'] = s.id request.session['type'] = 'survey' # no data to show return render_to_response('gender.html', {}, context_instance=RequestContext(request))
def post(self): going_gol, back_gol = gol_parse(gol_data()) going_tam, back_tam = tam_parse(tam_data()) s = Survey() s.date = datetime.now() for flight in going_gol: f = Flight(flight, True) f.company = 'GOL' s.flights.append(f) for flight in back_gol: f = Flight(flight, False) f.company = 'GOL' s.flights.append(f) for flight in going_tam: f = Flight(flight, True) f.company = 'TAM' s.flights.append(f) for flight in back_tam: f = Flight(flight, False) f.company = 'TAM' s.flights.append(f) db.session.add(s) db.session.commit() return s.serialize
def example(): survey = Survey.collection.find_one({'user':request.user,'name':'example'}) if not survey: survey = Survey(fields = {},authorized_keys = [],authorized_keys_only = False,key = uuid.uuid4().hex,name = "example",user = request.user) survey.save() context = {'survey' : survey} response = make_response(render_template("example.html",**context)) return response
def generate(): list = [10007, 3011, 2007, 5009, 9007, 16001, 17001] shuffle(list) survey = Survey.get_by_id(list) for surveyobj in survey: survey2 = clone_entity(surveyobj) survey2.put() surveys = Survey.all() return render_template('survey_answers.html', surveys=surveys)
def create_survey(): form = NewSurveyForm(request.form) surveys = db.session.query(Survey).all() new_survey = Survey(**form.data) new_survey.body = json.loads(form.data['body']) db.session.add(new_survey) db.session.commit() return render_template('surveys.html', surveys=surveys, form=form)
def create_a_survey(request): # create a survey # create a survey object # get input from createSurvey.html # return HttpResponse('create a survey ') logging.debug(request.POST) survey_name = request.POST['SurveyName'] s = Survey(survey=survey_name, pub_date=datetime.date.today(), author=request.user.username, popularity=0) s.save() # response to /s.id/addPolls return HttpResponseRedirect('createSurveyPage')
def addsurvey(): if request.method == 'POST': name = request.get_json().get('name') session.add(Survey(name=name)) output = "Record Added" session.commit() return make_response(output)
def handleForm(request): new_title = request.POST['title'] new_author = request.POST['author'] new_desc = request.POST['desc'] answers = [] for i in range(1, 20): input_name = "answer" + str(i) if input_name in request.POST: s = request.POST[input_name].replace("'", "") answers.append(s) new_survey = Survey(title=new_title, author=new_author, desc=new_desc) new_survey.save() for answer in answers: new_answer = Answer(survey=new_survey, text=answer, votes=0) new_answer.save() return HttpResponseRedirect('/survey/' + str(new_survey.id))
def get(self): parser = reqparse.RequestParser() parser.add_argument('id', help='This field cannot be blank', required=True, location='headers') data = parser.parse_args() survey = Survey.find_by_id(data['id']) if not survey: return {'message': f"Survey {data['id']} doesn\'t exist"} stats = [] for i, q in enumerate(survey.questions): q_stat = { 'id': q.idQuestion, 'type': q.type, 'votes': q.count_replies(q.idQuestion), 'content': q.content, 'answers': [x.reply for x in q.replies] } stats.append(q_stat) return stats
def add_survey(): if request.form: newSurvey = Survey(title=request.form.get('title'), category=request.form.get('category'), nbOfQuestions=int( request.form.get('nbOfQuestions')), idU=request.form.get('idU')) db.session.add(newSurvey) db.session.commit() return redirect("/")
def one(self, id_): if request.method == 'GET': survey = Survey.query.get(id_) return jsonify(survey.to_dict()) elif request.method == 'PUT': data = request.get_json() for q in data['questions']: choice = Choice.query.get(q['choice']) choice.selected = choice.selected + 1 choice.save() survey = Survey.find(data['id']) return jsonify(survey.to_dict()), 201
def survey(self,message, fname , lname, gender ,age, activity ): if gender == 'M': sex = 'Male' else: sex = 'Female' if activity == '1': prof = 'Student' else: prof = 'Professional' act = Activities.objects.get(code=activity) survey = Survey(firsName=fname , lastName=lname, sex=gender, age=age, activity=act, enteredDate = date.today() ) try: survey.save() message.respond(u"You have entered first name :%s. last name: %s. gender: %s. age: %s. activity: %s. " %((fname,lname,sex,age,prof))) except: message.respond(u"Faild to insert") return True
def gender(request): if not request.session : # if it doesn't have a session -> start again return render_to_response('start', {'error_message': "Your session had time out. Start again.", }, context_instance=RequestContext(request)) logging.info('<gender> sid: {} , POST:{}'.format(request.session.session_key, request.POST)) if 'survey_id' in request.session: del request.session['survey_id'] if request.POST['answer'] == 'Skip survey': request.session['type'] = 'skip' # return render_to_response('index.html', {}, context_instance=RequestContext(request)) return HttpResponseRedirect(reverse('openday.views.app')) # create new survey s = Survey() s.survey_date = datetime.datetime.now() s.save() request.session['survey_id'] = s.id request.session['type'] = 'survey' # no data to show return render_to_response('gender.html', {}, context_instance=RequestContext(request))
def survey_add(request): if request.method == 'POST': form = SurveyForm(request.POST) has_errors = False try: newSurvey = Survey() name = request.POST.get('name') newSurvey.name = name title = request.POST.get('title') newSurvey.title = title datastore = request.POST.get('datastore') newSurvey.datastore_id = datastore exists = False projects = Project.objects.all() for p in projects: if name == p.name: exists = True if name == '': message = _(u'You must enter an survey name') return render(request, 'survey_add.html', {'message': message, 'form': form}) if _valid_name_regex.search(name) == None: message = _(u"Invalid survey name: '{value}'. Identifiers must begin with a letter or an underscore (_). Subsequent characters can be letters, underscores or numbers").format(value=name) return render(request, 'survey_add.html', {'message': message, 'form': form}) if not exists: newSurvey.save() return redirect('survey_update', survey_id=newSurvey.id) else: message = _(u'Exists a project with the same name') return render(request, 'survey_add.html', {'message': message, 'form': form}) #msg = _("Error: fill all the survey fields") #form.add_error(None, msg) except Exception as e: try: msg = e.get_message() except: msg = _("Error: survey could not be published") form.add_error(None, msg) else: form = SurveyForm() return render(request, 'survey_add.html', {'form': form})
def create(self, survey_name): survey = Survey(name=survey_name.lower(), pretty_name=survey_name, language='en') db.session.add(survey) try: db.session.flush() self._replace_survey_questions(survey=survey, questions=default_stack) self._generate_multicolumn_index(survey) db.session.commit() return survey except IntegrityError: db.session.rollback()
def all(self): if request.method == 'GET': surveys = Survey.all() return jsonify([s.to_dict() for s in surveys]) elif request.method == 'POST': data = request.get_json() survey = Survey(name = data['name']) questions = [] for q in data['questions']: question = Question(text = q['text']) question.choices = [Choice(text = c) for c in q['choices']] questions.append(question) survey.questions = questions survey.save() return jsonify(survey.to_dict()), 201
def post(self): args = parser.parse_args() response = {} survey = Survey(args['code'], args['proficiency'], args['experience'], args['education'], args['interrupted']) db.session.add(survey) db.session.commit() response['error'] = False response['survey'] = { 'code': survey.code, 'proficiency': survey.proficiency, 'experience': survey.experience, 'education': survey.education, 'interrupted': survey.interrupted } return response
def prepopulate(db, survey_schema_fn): survey_schema = read_schema(survey_schema_fn) survey_name = survey_schema['surveyName'] language = survey_schema['language'] survey = Survey(name=survey_name.lower(), pretty_name=survey_name, language=language) db.session.add(survey) db.session.commit() survey_questions = default_stack + survey_schema['surveyQuestions'] load_survey_questions(db, survey, survey_questions) load_survey_prompts(db, survey, prompts=survey_schema['surveyPrompts']) create_admin_user(db, survey, survey_schema['adminEmail'], survey_schema['adminPassword']) db.session.commit()
def register_survey(survey_id): survey = request.get_json() survey_size = survey['size'] survey_title = survey['title'] survey_subtitle = survey['subtitle'] user = User.query.filter_by(id=session['userid']).first() if user.q_point < 100: return jsonify({'result': 'q_shortage'}) user.q_point -= 100 question_len = len(session['tmp_question_dict'][survey_id]) if question_len < 5: survey_que = question_len * 10 else: survey_que = 50 survey = Survey(link=survey_id, title=survey_title, subtitle=survey_subtitle, userID=user.id, que=survey_que) db.session.add(survey) db.session.commit() db.session.flush() session['userid'] = user.id print 'question dict', session['tmp_question_dict'][survey_id] for question_idx, each_question in session['tmp_question_dict'][ survey_id].iteritems(): print 'value', each_question question = Question(title=each_question['title'], subtitle=each_question['subtitle'], questionType=each_question['type'], isEssential=True, surveyID=survey.id) db.session.add(question) db.session.commit() db.session.flush() question = Question.query.filter_by(title=question.title).first() for each_option in each_question['option']: option = Option(content=each_option, questionID=question.id) db.session.add(option) db.session.commit() db.session.flush() return jsonify({'result': 'success'})
def create_from_schema(self, survey_name, admin_email, admin_password, language, survey_questions, survey_prompts): try: with db.session.begin_nested(): survey = Survey(name=survey_name.lower(), pretty_name=survey_name, language=language) db.session.add(survey) hardcoded_questions = default_stack + survey_questions self._load_survey_questions(survey=survey, questions=hardcoded_questions) self._load_survey_prompts(survey=survey, prompts=survey_prompts) self._create_admin(survey, admin_email, admin_password) db.session.commit() except IntegrityError as e: db.session.rollback() return e.message
def create(): session['tmp_question_dict'] = {} if request.method == 'GET': current_time = datetime.datetime.now().strftime("%Y-%m-%d,%H:%M:%S") print current_time print session['userid'] hash = hashlib.md5(str(session['userid']) + current_time).hexdigest() return redirect('survey/' + hash + '/edit') else: survey_title = request.form['survey_title'] survey_subtitle = request.form['survey_subtitle'] question_type = request.form['question_type'] isEssential = request.form['is_essential'] userid = session['userid'] survey = Survey(title=title, subtitle=subtitle, userID=userid) db.session.add(survey) db.session.commit() # question = Question(title=survey_title, subtitle=survey_subtitle, questionType=question_type, surveyID) return render_template("create.html")
def complete(module_number, submodule_number): if not allowed_submodule(module_number - 1, submodule_number - 1): abort(404) if request.method == 'GET': return render_template('survey.jinja2') q1 = request.form.get('q1') q2 = request.form.get('q2') q3 = request.form.get('q3') q4 = request.form.get('q4') q5 = request.form.get('q5') if not q1 or not q2 or not q3 or not q4 or not q5: return render_template('survey.jinja2', fail=True) survey = Survey(username=current_user.username, module=module_number - 1, submodule=submodule_number - 1,\ responses=[q1] + [q2] + [q3] + [q4] + [q5]) db.session.add(survey) if submodule_number < num_submodules()[module_number - 1]: current_user.locked_sub[module_number - 1][submodule_number] = False flag_modified(current_user, 'locked_sub') db.session.commit() return redirect('/modules/' + str(module_number))
def survey(): post_data = request.get_json() survey_data = Survey( dryness = post_data["dryness"], oiliness = post_data["oiliness"], redness = post_data["redness"], sensitivity = post_data["sensitivity"], acne = post_data["acne"], wrinkles = post_data["wrinkles"], scarring = post_data["scarring"] ) db.session.add(survey_data) db.session.commit() response_object = { 'status': 'success', 'message': 'Survey was added!' } return jsonify(response_object), 201
def store(): '''Salva i dati del questionario nel db''' # Set up data to store data = dict(request.args) type = 'POST' age = None if data.get('history') == 'NA': type = 'PRE' if data.get('age') != '': age = data.put('age') survey = Survey(data.get('tag'), classtoken, type, data.get('path'), data.get('history'), data.get('gender'), age, data.get('residence'), data.get('q1'), data.get('q2'), data.get('q3'), data.get('q4'), data.get('q5'), data.get('q6'), data.get('q7'), data.get('q8'), data.get('q9'), data.get('freetext')) db_session.add(survey) db_session.commit() return render_template('credits.html', type=type, path=data.get('path'))
def post(self): current_username = get_jwt_identity() u = User.find_by_username(current_username) parser = reqparse.RequestParser() parser.add_argument('name', help='This field cannot be blank', required=True, location='headers') parser.add_argument('desc', location='headers') parser.add_argument('duedate', help='This field cannot be blank', required=True, location='headers') parser.add_argument('isactive', location='headers') parser.add_argument('questions', action='append') data = parser.parse_args() boolActive = True if hasattr( data, 'isactive') and data['isactive'] == 'True' else False new_survey = Survey(name=data['name'], desc=data['desc'], dueDate=data['duedate'], isActive=boolActive, idUser=u.idUser) try: new_survey.flush_to_db() except: return {'message': 'Something went wrong'}, 500 print("Survey zapisany, teraz questions") if not data.questions == None: for i in data.questions: dict = ast.literal_eval(i) print(dict) new_question = Question(content=dict['content'], type=dict['type'], replyContent=dict['replyContent'], idSurvey=new_survey.idSurvey) new_question.save_to_db() new_survey.commit_to_db() return {'message': 'Survey {} was created'.format(data['name'])}
def store_surveys_to_db(db_session, requests_session): surveys_by_hash_id = { obj.public_hash_id: obj for obj in db_session.query(Survey).all() } res = [] for survey in get_surveys(requests_session): if not filter_survey(survey): continue res.append(survey['public_hash_id']) survey_obj = surveys_by_hash_id.get(survey['public_hash_id']) if survey_obj: survey_obj.title = survey['title'] survey_obj.status = survey['status'] db_session.commit() else: db_session.add( Survey( title=survey['title'], public_hash_id=survey['public_hash_id'], status=survey['status'], )) db_session.commit() return res
def surveyAddAction(request): # print request.REQUEST # 读取问卷标识 paperIdSigned = request.REQUEST['paperId'] # 验证问卷的数字签名 sign = Signer() paperId = sign.unsign(paperIdSigned) # print 'paperId=', paperId # 检查用户的登录状态 user = getCurrentUser(request) if user is None: raise Exception(u'没有登录') # 读取问卷并创建实例 paper = Paper.objects.get(id=paperId) paperInstance = paper.createPaperInstance(user) # 如果文件设置了跳转,但其step却设置为False,这样很容易造成困扰 # 这里对问卷在发布的时候强行修改step为True if paperInstance.isStepNeed(): paperInstance.step = True paperInstance.save() # 创建survey对象 survey = Survey() updateModelInstance(survey, request.REQUEST, tryUnsigned=True) survey.paper = paperInstance survey.createBy = user survey.modifyBy = user survey.save() # 设置文件到调查的反向连接,主要用于级联删除时使用 paperInstance.survey = survey paperInstance.save() # 返回调查列表 return HttpResponseRedirect(reverse('survey:view.survey.publish', args=[survey.id]))
def paperPreview(request, paperId): ''' 问卷预览 ''' # 检查用户的登录状态 user = getCurrentUser(request) if user is None: raise Exception(u'没有登录') # 读取问卷并创建实例 paper = Paper.objects.get(id=paperId) if paper.createBy != user: raise Exception(u'没有权限预览该问卷') # 在系统系统管理源的名下创建一个调查 admin = User.objects.get(code='admin') paperInstance = paper.createPaperInstance(admin) # 如果文件设置了跳转,但其step却设置为False,这样很容易造成困扰 # 这里对问卷在发布的时候强行修改step为True if paperInstance.isStepNeed(): paperInstance.step = True paperInstance.save() # 创建survey对象 survey = Survey() survey.paper = paperInstance survey.createBy = admin survey.modifyBy = admin survey.save() # 清理之前的预览对象, 关联当前预览对象 if paper.previewSurvey: paper.previewSurvey.delete() paper.previewSurvey = survey paper.save() # 返回答题界面 return HttpResponseRedirect(reverse('survey:view.survey.answer', args=[survey.id]))
from app import db from models import Survey, Task, Assignment, Response import os try: os.remove("sample.db") except: pass db.create_all() survey = Survey() task = Task() assignment = Assignment() fileNames = ["file1.mp3", "file2.mp3", "file3.mp3", "file4.mp3"] answers = ["A", "B", "C", "D", "E"] counts = [] counts.append([10, 8, 5, 0, 1]) counts.append([1, 26, 2, 3, 7]) counts.append([4, 0, 0, 3, 57]) counts.append([1, 6, 1, 5, 28]) index = 0 for i in range(0, len(fileNames)): answerCounts = counts[i] for j in range(0, len(answerCounts)): for k in range(0, answerCounts[j]):
def survey_create(request): newSurvey = Survey() newSurvey.title = request.POST['survey_title'] newSurvey.save() request.session['current_survey'] = newSurvey.id return redirect('admin-question-add-view')
def survey(): form = SurveyForm() if form.validate_on_submit(): if form.purchase_online.data == 'false': last_purchase = 'none' purchase_frequency = 'none' else: last_purchase = form.last_purchase.data purchase_frequency = form.purchase_frequency.data survey = Survey( sex=form.sex.data, comment=form.comment.data, age=form.age.data, martial_status=form.martial_status.data, internet_usage=form.internet_usage.data, internet_frequency=form.internet_frequency.data, purchase_online=form.purchase_online.data, purchase_frequency=purchase_frequency, last_purchase=last_purchase, employment_status=form.employment_status.data, income_range=form.income_range.data, q01_1=int(form.q01_1.data), q01_2=int(form.q01_2.data), q02_1=int(form.q02_1.data), q02_2=int(form.q02_2.data), q03_1=int(form.q03_1.data), q03_2=int(form.q03_2.data), q04_1=int(form.q04_1.data), q04_2=int(form.q04_2.data), q05_1=int(form.q05_1.data), q05_2=int(form.q05_2.data), q06_1=int(form.q06_1.data), q06_2=int(form.q06_2.data), q07_1=int(form.q07_1.data), q07_2=int(form.q07_2.data), q08_1=int(form.q08_1.data), q08_2=int(form.q08_2.data), q09_1=int(form.q09_1.data), q09_2=int(form.q09_2.data), q10_1=int(form.q10_1.data), q10_2=int(form.q10_2.data), q11_1=int(form.q11_1.data), q11_2=int(form.q11_2.data), q12_1=int(form.q12_1.data), q12_2=int(form.q12_2.data), q13_1=int(form.q13_1.data), q13_2=int(form.q13_2.data), q14_1=int(form.q14_1.data), q14_2=int(form.q14_2.data), q15_1=int(form.q15_1.data), q15_2=int(form.q15_2.data), q16_1=int(form.q16_1.data), q16_2=int(form.q16_2.data), q17_1=int(form.q17_1.data), q17_2=int(form.q17_2.data), q18_1=int(form.q18_1.data), q18_2=int(form.q18_2.data), q19_1=int(form.q19_1.data), q19_2=int(form.q19_2.data), q20_1=int(form.q20_1.data), q20_2=int(form.q20_2.data), q21_1=int(form.q21_1.data), q21_2=int(form.q21_2.data), q22_1=int(form.q22_1.data), q22_2=int(form.q22_2.data), q23_1=int(form.q23_1.data), q23_2=int(form.q23_2.data), q24_1=int(form.q24_1.data), q24_2=int(form.q24_2.data), q25_1=int(form.q25_1.data), q25_2=int(form.q25_2.data), q26_1=int(form.q26_1.data), q27_1=int(form.q27_1.data), ) try: survey.put() flash(u'Thank you', 'success') return redirect(url_for('thankyou')) except CapabilityDisabledError: flash(u'App Engine Datastore is currently in read-only mode.', 'info') return redirect(url_for('home')) return render_template('survey.html', form=form)
def survey_answers(): surveys = Survey.all() surveys.order('timestamp') surveys.fetch(limit=5) return render_template('survey_answers.html', surveys=surveys)
def survey_create(request): newSurvey=Survey() newSurvey.title=request.POST['survey_title'] newSurvey.save() request.session['current_survey']=newSurvey.id return redirect('admin-question-add-view')