def delete(self, survey_id, action = 'self'): if current_user.is_authenticated(): try: s_id = HashId.decode(survey_id) svey = Survey.objects(id = s_id).first() if svey is None: raise TypeError if svey.hidden: raise APIException("This Survey has already been deleted", 404) except TypeError: raise APIException("Invalid Survey ID", 404) if action == 'self': svey.hidden = True svey.save() ret = { 'id': str(svey), 'field': action, 'saved': True, } return ret, 200 elif action == 'img': args = self.post_args() dat = args['swag'] try: im_id = HashId.decode(dat) img = AttachmentImage.objects(id = im_id).first() if img is None: raise TypeError if img.hidden: raise APIException("This Image has already been deleted", 404) img.hidden = True svey.attachments.remove(img) img.save() svey.save() ret = { 'id': str(svey), 'img_id': str(img), 'field': action, 'saved': True, } return ret, 200 except (TypeError, ValueError): raise APIException("Invalid Image ID", 404) else: raise APIException("Login Required", 401)
def delete(self, survey_id, action = 'self'): if current_user.is_authenticated(): try: s_id = HashId.decode(survey_id) svey = Survey.objects(id = s_id).first() if svey is None: raise TypeError if svey.hidden: raise APIException("This Survey has already been deleted", 404) except TypeError: raise APIException("Invalid Survey ID", 404) if action == 'self': svey.hidden = True svey.save() ret = { 'id': str(svey), 'field': action, 'saved': True, } return ret, 200 elif action == 'img': args = self.post_args() dat = args['swag'] try: im_id = HashId.decode(dat) img = AttachmentImage.objects(id = im_id).first() if img is None: raise TypeError if img.hidden: raise APIException("This Image has already been deleted", 404) img.hidden = True svey.attachments.remove(img) img.save() svey.save() ret = { 'id': str(svey), 'img_id': str(img), 'field': action, 'saved': True, } return ret, 200 except (TypeError, ValueError): raise APIException("Invalid Image ID", 404) else: raise APIException("Login Required", 401)
def get(self,survey_id,aggregate="false"): ##First get for all surveys survey_id=HashId.decode(survey_id) # survey_id=HashId.decode("goojkg5jyVnGj9V6Lnw") # parent_survey=survey_id # survey_id= HashId.decode("3NNl87yvoZXN4lypAjq") parent_survey= survey_id l = IrapiData(survey_id,1,1,aggregate) # survey_strct= l.survey_strct() #Check if survey has children. #Check for parent too. flag0= l.get_parent() if flag0!=False: """There is a parent""" parent_survey= flag0 flag= l.flag() if flag ==False: r= {} r['parent_survey']= self.logic(survey_id,parent_survey,aggregate) return r else: if aggregate=="true": response={} response['parent_survey']= self.logic(survey_id,parent_survey,aggregate) # return self.logic(survey_id,parent_survey) # response={} units=[] for i in flag: units.append(self.logic(HashId.decode(i),parent_survey,aggregate)) # return response units.append(self.logic(survey_id,parent_survey,"false")) response['units']=units return response else: r= {} r['parent_survey']= self.logic(survey_id,parent_survey,aggregate) return r
def get(self, survey_id, action = 'repr'): args = self.get_args() try: s_id = HashId.decode(survey_id) svey = Survey.objects(id = s_id).first() if svey is None: raise TypeError if svey.hidden: raise APIException("This Survey has been deleted", 404) except TypeError: raise APIException("Invalid Survey ID", 404) if action == 'json': if args['editing'] == 'true': return svey.struct try: return svey.render_json except TypeError as e: raise APIException(str(e), 400) elif action == 'deepjson': return svey.render_deepjson elif action == 'repr': return svey.repr raise APIException("Must specify a valid option", 400)
def get(self, survey_id, action = 'repr'): args = self.get_args() try: s_id = HashId.decode(survey_id) svey = Survey.objects(id = s_id).first() if svey is None: raise TypeError if svey.hidden: raise APIException("This Survey has been deleted", 404) except TypeError: raise APIException("Invalid Survey ID", 404) if action == 'json': if args['editing'] == 'true': return svey.struct try: return svey.render_json except TypeError as e: raise APIException(str(e), 400) elif action == 'deepjson': return svey.render_deepjson elif action == 'repr': return svey.repr raise APIException("Must specify a valid option", 400)
def get(self,survey_id,aggregate="false"): ##First get for all surveys survey_id=HashId.decode(survey_id) # survey_id=HashId.decode("goojkg5jyVnGj9V6Lnw") # parent_survey=survey_id # survey_id= HashId.decode("3NNl87yvoZXN4lypAjq") parent_survey= survey_id l = IrapiData(survey_id,1,1,aggregate) # survey_strct= l.survey_strct() #Check if survey has children. #Check for parent too. flag0= l.get_parent() if flag0!=False: """There is a parent""" parent_survey= flag0 flag= l.flag() if flag ==False: r= {} r['parent_survey']= self.logic(survey_id,parent_survey,aggregate) return r else: if aggregate=="true": response={} response['parent_survey']= self.logic(survey_id,parent_survey,aggregate) units=[] for i in flag: units.append(self.logic(HashId.decode(i),parent_survey,aggregate)) # return response units.append(self.logic(survey_id,parent_survey,"false")) response['units']=units # return "true" return response else: r= {} r['parent_survey']= self.logic(survey_id,parent_survey,aggregate) return r
def get_multi_data(self, aList): js = [] # return aLists for i in aList: i = HashId.decode(i) raw = db.response.find({"parent_survey": ObjectId(i)}) js = js + d(raw) return js
def get_multi_data(self,aList): js=[] # return aLists for i in aList: i= HashId.decode(i) raw= db.response.find({"parent_survey":ObjectId(i)}) js= js +d(raw) return js
def survey_strct(self): try: raw=Survey.objects(id = HashId.decode(self.sid)) except: raw=Survey.objects(id = self.sid) js=raw[0]['structure']['fields'] # js=raw[0] return js
def getInsights(self): raw_data = Insights.objects(survey_id = HashId.encode(self.sid)) if len(raw_data) == 0: return None unordered_insight_dict = d(raw_data[0].insights) ordered_dates_list = sorted(unordered_insight_dict, key = lambda t: datetime.datetime.strptime(t, '%d-%m-%Y'), reverse=True) ordered_insights_list = [] for i in ordered_dates_list: ordered_insights_list.append([i, list(unordered_insight_dict[i].values())]) return ordered_insights_list
def get_analysis_page(survey_id): try: s_id = HashId.decode(survey_id) svey = Survey.objects(id = s_id).first() if svey is None: raise TypeError except TypeError: raise ViewException("Invalid Survey ID", 404) return render_template('survaiderdashboard/index.analysis.html', title = "Analytics", survey = svey.repr)
def get_analysis_page(survey_id): try: s_id = HashId.decode(survey_id) svey = Survey.objects(id = s_id).first() if svey is None: raise TypeError except TypeError: raise ViewException("Invalid Survey ID", 404) return render_template('srvy.analysis.html', title = "Analytics", survey = svey.repr)
def getLeaderboard(self): raw_data = Leaderboard.objects(survey_ID = HashId.encode(self.sid)) if len(raw_data) == 0: return None ordered_leaderboard_list = [] unordered_leaderboard_dict = d(raw_data[0].competitors) ordered_scores_list = sorted(unordered_leaderboard_dict, key = unordered_leaderboard_dict.get, reverse=True) for i in ordered_scores_list: ordered_leaderboard_list.append([i, unordered_leaderboard_dict[i]]) return ordered_leaderboard_list
def get(self, survey_id, response_id): try: s_id = HashId.decode(survey_id) svey = Survey.objects(id = s_id).first() if svey is None: raise TypeError("Invalid Survey ID") if svey.hidden: raise APIException("This Survey has been deleted", 404) r_id = HashId.decode(response_id) res = Response.objects(id = r_id, parent_survey = s_id).first() if res is None: raise TypeError("Invalid Response ID") except TypeError as e: ret = str(e) if len(str(e)) > 0 else "Invalid Hash ID" raise APIException(ret, 404) return json.loads(res.to_json()), 201
def get(self, survey_id, response_id): try: s_id = HashId.decode(survey_id) svey = Survey.objects(id = s_id).first() if svey is None: raise TypeError("Invalid Survey ID") if svey.hidden: raise APIException("This Survey has been deleted", 404) r_id = HashId.decode(response_id) res = Response.objects(id = r_id, parent_survey = s_id).first() if res is None: raise TypeError("Invalid Response ID") except TypeError as e: ret = str(e) if len(str(e)) > 0 else "Invalid Hash ID" raise APIException(ret, 404) return json.loads(res.to_json()), 201
def get(self, survey_id): """ GET /api/survey/<survey_id>/response Returns whether any valid response object for the <survey_id> exists in the Collection. It is up to the Client Code to implement saving of the responses so that the survey can be continued even after it is terminated pre-maturely. For security, the responses are NOT returned. Args: new (bool): Send a True GET parameter in URL to end the currently running response. Example: GET /api/survey/<survey_id>/response?new=true """ try: s_id = HashId.decode(survey_id) svey = Survey.objects(id = s_id).first() if svey is None: raise TypeError if svey.hidden: raise APIException("This Survey has been deleted", 404) except TypeError: raise APIException("Invalid Survey ID", 404) args = self.get_args() is_running = ResponseSession.is_running(s_id) ret = { 'response_session_running': is_running, 'will_accept_response': svey.active, 'will_end_session': False, 'is_expired': svey.expires <= datetime.datetime.now(), 'is_paused': svey.paused, 'is_active': svey.active, 'expires': str(svey.expires), } if is_running: "End The Existing Survey." if args['new']: ResponseSession.finish_running(s_id) ret['will_accept_response'] = False ret['will_end_session'] = True return ret, 201
def get(self, survey_id): """ GET /api/survey/<survey_id>/response Returns whether any valid response object for the <survey_id> exists in the Collection. It is up to the Client Code to implement saving of the responses so that the survey can be continued even after it is terminated pre-maturely. For security, the responses are NOT returned. Args: new (bool): Send a True GET parameter in URL to end the currently running response. Example: GET /api/survey/<survey_id>/response?new=true """ try: s_id = HashId.decode(survey_id) svey = Survey.objects(id = s_id).first() if svey is None: raise TypeError if svey.hidden: raise APIException("This Survey has been deleted", 404) except TypeError: raise APIException("Invalid Survey ID", 404) args = self.get_args() is_running = ResponseSession.is_running(s_id) ret = { 'response_session_running': is_running, 'will_accept_response': svey.active, 'will_end_session': False, 'is_expired': svey.expires <= datetime.datetime.now(), 'is_paused': svey.paused, 'is_active': svey.active, 'expires': str(svey.expires), } if is_running: "End The Existing Survey." if args['new']: ResponseSession.finish_running(s_id) ret['will_accept_response'] = False ret['will_end_session'] = True return ret, 201
def get_index(survey_id): try: s_id = HashId.decode(survey_id) svey = Survey.objects(id = s_id).first() if svey is None: raise TypeError if svey.hidden: raise ViewException("This Survey has been deleted.", 404) except TypeError: raise ViewException("Invalid Survey ID", 404) return render_template('srvy.index.html', title = "Editing Survaider", survey = svey)
def get_multi_data(self, aList): js=[] for i in aList: child_id= HashId.decode(i) # print (child_id) raw = Response.objects(parent_survey=child_id) raw_temp=[] for i in raw: temp_j=[] temp_j.append(i.responses) temp_j.append(i.metadata) raw_temp.append(temp_j) js= js + raw_temp return js
def get_simple_survey(survey_id): try: s_id = HashId.decode(survey_id) svey = Survey.objects(id = s_id).first() if svey is None: raise TypeError if not svey.active: raise ViewException("This Survey is not accepting Responses at this moment", 403) except TypeError: raise ViewException("Invalid Survey ID", 404) return app.send_static_file('simplesurvey/index.simplesurvey.html')
def get_simple_survey(survey_id): try: s_id = HashId.decode(survey_id) svey = Survey.objects(id = s_id).first() if svey is None: raise TypeError if not svey.active: raise ViewException("This Survey is not accepting Responses at this moment", 403) except TypeError: raise ViewException("Invalid Survey ID", 404) return app.send_static_file('simplesurvey/index.simplesurvey.html')
def get_index(survey_id): try: s_id = HashId.decode(survey_id) svey = Survey.objects(id = s_id).first() if svey is None: raise TypeError if svey.hidden: raise ViewException("This Survey has been deleted.", 404) except TypeError: raise ViewException("Invalid Survey ID", 404) return render_template('srvy.index.html', title = "Editing Survaider", survey = svey)
def get_gamified_survey(survey_id): try: s_id = HashId.decode(survey_id) svey = Survey.objects(id = s_id).first() if svey is None: raise TypeError if not svey.active: raise ViewException("This Survey is not accepting Responses at this moment", 403) if not svey.gamified_enabled: raise ViewException("This Survey cannot be rendered as a Game.", 403) except TypeError: raise ViewException("Invalid Survey ID", 404) return app.send_static_file('gamified/index.html')
def get_uuid_label(self): """labels: question text ; options ; etc""" #Extract the particular cid from the survey structure # raw_label=db.survey.find() #returns empty # raw_label=db.survey.find({"_id":ObjectId(self.sid)}) try: raw_label=Survey.objects(id = HashId.decode(self.sid)) except: raw_label=Survey.objects(id = self.sid) # return d(raw_label) aList= raw_label[0].structure['fields'] #A backup liseturn aList # return aList # aList= d(raw_label) # return aList for i in aList: if i['cid']==self.uuid: return i
def get_gamified_survey(survey_id): try: s_id = HashId.decode(survey_id) svey = Survey.objects(id = s_id).first() if svey is None: raise TypeError if not svey.active: raise ViewException("This Survey is not accepting Responses at this moment", 403) if not svey.gamified_enabled: raise ViewException("This Survey cannot be rendered as a Game.", 403) except TypeError: raise ViewException("Invalid Survey ID", 404) return app.send_static_file('gamified/index.html')
def get(self, survey_id, action = 'flat'): try: s_id = HashId.decode(survey_id) svey = Survey.objects(id = s_id).first() if svey is None: raise TypeError if svey.hidden: raise APIException("This Survey has been deleted", 404) except TypeError: raise APIException("Invalid Survey ID", 404) responses = ResponseAggregation(svey) if action == 'flat': return responses.flat(), 201 elif action == 'nested': return responses.nested(), 201 raise APIException("Must specify a valid option", 400)
def get(self, survey_id, action = 'flat'): try: s_id = HashId.decode(survey_id) svey = Survey.objects(id = s_id).first() if svey is None: raise TypeError if svey.hidden: raise APIException("This Survey has been deleted", 404) except TypeError: raise APIException("Invalid Survey ID", 404) responses = ResponseAggregation(svey) if action == 'flat': return responses.flat(), 201 elif action == 'nested': return responses.nested(), 201 raise APIException("Must specify a valid option", 400)
def post(self, survey_id): """ POST /api/survey/<survey_id>/response Saves the Question Responses. The responses are saved atomically. Aggregate saving of the responses is NOT implemented yet, since the game requires atomic response storage. Appends to the existing response document if it exists, otherwise creats a new document. Args: q_id (str): Question ID, as generated in the survey structure. q_res (str): Response. """ try: s_id = HashId.decode(survey_id) svey = Survey.objects(id = s_id).first() if svey is None: raise TypeError if svey.hidden: raise APIException("This Survey has been deleted", 404) except TypeError: raise APIException("Invalid Survey ID", 404) if not svey.active: raise APIException("This Survey is Inactive or is not accepting responses anymore.", 403) resp = None ret = { "existing_response_session": False, "new_response_session": False, "will_add_id": None, } if ResponseSession.is_running(svey.id): "Uses existing Response Session." ret['existing_response_session'] = True resp_id = ResponseSession.get_running_id(s_id) resp = Response.objects(id = resp_id).first() else: "Creates a New Response Session." ret['new_response_session'] = True resp = Response(parent_survey = svey) resp.metadata['started'] = datetime.datetime.now() resp.save() ResponseSession.start(s_id, resp.id) args = self.post_args() try: resp.add(args['q_id'], args['q_res']) ret['will_add_id'] = args['q_id'] except TypeError as te: raise APIException(str(te), 400) return ret, 200
def get(self,survey_id,start=None,end=None,aggregate="false"): try: survey_id=HashId.decode(survey_id) except ValueError: return "No survey_id or uuid provided" lol = IrapiData(survey_id,start,end,aggregate) all_responses= lol.get_data() # return all_responses #return all_responses all_survey= lol.get_uuid_labels() if "referenced" in all_survey[0]: parent_survey= all_survey[0]['referenced']['$oid'] # parent_survey= HashId.decode(parent_survey) s= IrapiData(parent_survey,start,end,aggregate) all_survey=s.get_uuid_labels() else: all_survey= lol.get_uuid_labels() # return all_responses # try: # all_survey=all_survey[0] # except : # pass ret=[] # return all_survey for i in range(len(all_survey)): j_data=all_survey[i] uuid= j_data['cid'] response_data=all_responses try: options=[] option_code={} for i in range(len(j_data['field_options']['options'])): options.append(j_data['field_options']['options'][i]['label']) option_code["a_"+str(i+1)]=j_data['field_options']['options'][i]['label'] except:pass """Response Count """ temp=[] for a in range(len(response_data)): try: temp.append(response_data[a]['responses'][uuid]) except: pass """Option Count""" options_count={} options_count_segg={} sentiment={'positive':0,'negative':0,'neutral':0} long_text="" if j_data['field_type'] not in ["ranking","rating","group_rating"]: for b in temp: if j_data['field_type']=='long_text': dat= DatumBox() sent= dat.get_sentiment(b) sentiment[sent]+=1 options_count_segg[b]=sent long_text+=" "+b if j_data['field_type']=='multiple_choice': split_b= b.split('###') if len(split_b)==0: if split_b[0] in options_count_segg: options_count_segg[split_b[0]]+=1 else:options_count_segg[split_b[0]]=1 elif len(split_b)!=0: for i in split_b: if i in options_count_segg: options_count_segg[i]+=1 else:options_count_segg[i]=1 if b in options_count:pass else:options_count[b]=temp.count(b) elif j_data['field_type'] in ["ranking"]: values={} for c in temp:#temp is an array of responses aTempList=c.split("###") #split a##2###b##1### [ "a##1", "b##3", "c##2"] for d in aTempList: bTempList=d.split("##") #["a","1"] e= bTempList[0] #Values are a ,b rank_key= bTempList[1] #values are 1,2,3,4 if e in values: if rank_key in values[e]: values[e][rank_key]+=1 else: # values[e]={} values[e][rank_key]=1 else: values[e]={} values[e][rank_key]=1 if e in options_count: """ e is for eg : a_1 or a_2 aTempList is the total options bTempList is option:value pair """ options_count[e]=int(options_count[e])+len(aTempList)-int(bTempList[1]) else: options_count[e]=len(aTempList)-int(bTempList[1]) elif j_data['field_type']=="group_rating": for f in temp: aTempList=f.split("###") for g in aTempList: bTempList=g.split("##") l= bTempList[0] k=bTempList[1] if l in options_count: if k in options_count[l]: options_count[l][k]+=1 else:options_count[l][k]=1 else: options_count[l]={} options_count[l][k]=1 elif j_data['field_type']=="rating": for i in temp: i = str(i) if i in options_count: options_count[i]+=1 else:options_count[i]=1 #return options_count response={} response['cid']=uuid response['label']=j_data['label'] response['type']=j_data['field_type'] response['option_code']=option_code if j_data['field_type']!='long_text': response['options_count']=options_count if j_data['field_type']=='long_text': response['sentiment']=sentiment response['sentiment_segg']=options_count_segg keywords=dat.get_keywords(long_text) response['keywords']=keywords #response['garbage']=temp if j_data['field_type']=='ranking': response['ranking_count']=values if j_data['field_type']=='multiple_choice': response['options_count_segg']=options_count_segg response['total_resp']= len(temp) if j_data['field_type']=="rating": avg=0 for i in temp: avg+=int(i) # response['avg_rating']= float(avg)/float(len(temp)) response['avg_rating']= float(avg)/len(temp) if j_data['field_type']=="group_rating": avg={} for key in options_count: counter=0 for bkey in options_count[key]: if int(bkey)!=0: counter+=float(bkey)*options_count[key][bkey] else:pass avg[key]= round(float(counter)/len(temp),2) response['avg_rating']=avg ret.append(response) return ret
def get(self,survey_id,start=None,end=None,aggregate="false"): try: survey_id=HashId.decode(survey_id) except ValueError: return "No survey_id or uuid provided" lol = IrapiData(survey_id,start,end,aggregate) all_responses= lol.get_data() #return all_responses all_survey= lol.get_uuid_labels() if "referenced" in all_survey[0]: parent_survey= all_survey[0]['referenced']['$oid'] # parent_survey= HashId.decode(parent_survey) s= IrapiData(parent_survey,start,end) all_survey=s.get_uuid_labels() else: all_survey= lol.get_uuid_labels() # return all_responses # try: # all_survey=all_survey[0] # except : # pass ret=[] # return all_survey for i in range(len(all_survey)): j_data=all_survey[i] uuid= j_data['cid'] response_data=all_responses try: options=[] option_code={} for i in range(len(j_data['field_options']['options'])): options.append(j_data['field_options']['options'][i]['label']) option_code["a_"+str(i+1)]=j_data['field_options']['options'][i]['label'] except:pass """Response Count """ temp=[] for a in range(len(response_data)): temp.append(response_data[a]['responses'][uuid]) """Option Count""" options_count={} if j_data['field_type'] not in ["ranking","rating","group_rating"]: for b in temp: if b in options_count:pass else:options_count[b]=temp.count(b) elif j_data['field_type'] in ["ranking"]: for c in temp: aTempList=c.split("###") for d in aTempList: bTempList=d.split("##") e= bTempList[0] if e in options_count: options_count[e]=int(options_count[e])+len(aTempList)-int(bTempList[1]) else: options_count[e]=len(aTempList)-int(bTempList[1]) elif j_data['field_type']=="group_rating": for f in temp: aTempList=f.split("###") for g in aTempList: bTempList=g.split("##") l= bTempList[0] k=bTempList[1] if l in options_count: if k in options_count[l]: options_count[l][k]+=1 else:options_count[l][k]=1 else: options_count[l]={} options_count[l][k]=1 elif j_data['field_type']=="rating": for i in temp: i = str(i) if i in options_count: options_count[i]+=1 else:options_count[i]=1 #return options_count response={} response['cid']=uuid response['label']=j_data['label'] response['type']=j_data['field_type'] response['option_code']=option_code response['options_count']=options_count response['total_resp']= len(temp) if j_data['field_type']=="rating": avg=0 for i in temp: avg+=int(i) # response['avg_rating']= float(avg)/float(len(temp)) response['avg_rating']= float(avg)/len(temp) if j_data['field_type']=="group_rating": avg={} for key in options_count: counter=0 for bkey in options_count[key]: if int(bkey)!=0: counter+=float(bkey)*options_count[key][bkey] else:pass avg[key]= round(float(counter)/len(temp),2) response['avg_rating']=avg ret.append(response) return ret
def get(self,survey_id,uuid,aggregate="false"): survey_id=HashId.decode(survey_id) #Uncomment on Production # survey_id="IamASurveyId" lol= DataSort(survey_id,uuid,aggregate) all_survey= lol.get_survey() if "referenced" in all_survey[0]: # return "reference" parent_survey= all_survey[0]['referenced']['$oid'] # parent_survey= HashId.decode(parent_survey) s= DataSort(parent_survey,uuid) survey_data= s.get_uuid_label() else: survey_data= lol.get_uuid_label() j_data= d(survey_data) #return j_data # Get Responses for a cid response_data= lol.get_data() #return j_data['field_options']['options'][0]['label'] # Options try: options=[] option_code={} for i in range(len(j_data['field_options']['options'])): options.append(j_data['field_options']['options'][i]['label']) option_code["a_"+str(i+1)]=j_data['field_options']['options'][i]['label'] except: return "error" #Response Count temp= [] for i in range(len(response_data)): temp.append(response_data[i]['responses'][uuid]) #eturn j_data['field_type'] options_count={} if j_data['field_type'] not in ["ranking","rating","group_rating"]: for i in temp: if i in options_count:pass else:options_count[i]= temp.count(i) elif j_data['field_type'] in ["ranking"]: for i in temp: aTempList= i.split("###") for j in aTempList: bTempList= j.split("##") l = bTempList[0] if l in options_count: options_count[l]= int(options_count[l])+len(aTempList)-int(bTempList[1]) else: options_count[l]=len(aTempList)-int(bTempList[1]) # elif j_data['field_type']=="rating": # for i in temp: # aTempList= i.split("###") #Check if this breaks the logic # for j in aTempList: # bTempList= j.split("##") # if j in options_count: # options_count[j]= int(options_count[j])+ int(bTempList[1]) # else: # options_count[j]= int(bTempList[1]) elif j_data['field_type']=="group_rating": for i in temp: aTempList= i.split("###") #options_count={} for j in aTempList: bTempList= j.split("##") l = bTempList[0] #o_c= {a_1:} k= bTempList[1] if l in options_count: if k in options_count[l]: options_count[l][k]+=1 else: options_count[l][k]=1 else: options_count[l]={} options_count[l][k]=1 elif j_data['field_type']=="rating": for i in temp: if str(i) in options_count: options_count[str(i)] +=1 else: options_count[str(i)]=1 # if int(i)>6: # if "above_5" in options_count: # options_count["above_5"]= options_count["above_5"]+1 # else: # options_count["above_5"]=1 # elif int(i)<6 and int(i)>3 : # if "above_3" in options_count: # options_count["above_3"]= options_count["above_3"]+1 # else: # options_count["above_3"]=1 # elif int(i)<=3: # if "below_3" in options_count: # options_count["below_3"]= options_count["below_3"]+1 # else: # options_count["below_3"]=1 # elif j_data['field_type']=="short_text": # return "lol" response= {} if j_data['field_type']=="rating": avg= 0 for i in temp: avg= avg + int(i) response['avg_rating']= round(float(avg)/float(len(temp))) if j_data['field_type']=="group_rating": avg={} for key in options_count: counter=0 for bkey in options_count[key]: if int(bkey)!=0: counter+= float(bkey) * options_count[key][bkey] else: pass avg[key]= round(float(counter)/len(temp),2) # avg[key]=float(sum(options_count[key].values()))/float(len(temp)) response['avg_rating']=avg response['cid']= uuid # survey_id= j_data['survey_id'] response['survey_id']=survey_id response['label']=j_data['label'] response['type']=j_data['field_type'] response['option_code']=option_code response['option_count']=options_count #return option_code response['total_resp']=len(temp) response['garbage']= temp return d(response)
def post(self, survey_id): """ POST /api/survey/<survey_id>/response Saves the Question Responses. The responses are saved atomically. Aggregate saving of the responses is NOT implemented yet, since the game requires atomic response storage. Appends to the existing response document if it exists, otherwise creats a new document. Args: q_id (str): Question ID, as generated in the survey structure. q_res (str): Response. """ try: s_id = HashId.decode(survey_id) svey = Survey.objects(id = s_id).first() if svey is None: raise TypeError if svey.hidden: raise APIException("This Survey has been deleted", 404) except TypeError: raise APIException("Invalid Survey ID", 404) if not svey.active: raise APIException("This Survey is Inactive or is not accepting responses anymore.", 403) resp = None ret = { "existing_response_session": False, "new_response_session": False, "will_add_id": None, } if ResponseSession.is_running(svey.id): "Uses existing Response Session." ret['existing_response_session'] = True resp_id = ResponseSession.get_running_id(s_id) resp = Response.objects(id = resp_id).first() else: "Creates a New Response Session." ret['new_response_session'] = True resp = Response(parent_survey = svey) resp.metadata['started'] = datetime.datetime.now() resp.save() ResponseSession.start(s_id, resp.id) args = self.post_args() try: resp.add(args['q_id'], args['q_res']) ret['will_add_id'] = args['q_id'] except TypeError as te: raise APIException(str(te), 400) return ret, 200
def __init__(self,survey_id): self.sid= HashId.decode(survey_id)
def __unicode__(self): return HashId.encode(self.id)
def __unicode__(self): return HashId.encode(self.id)
def get(self,survey_id,uuid,aggregate="false"): survey_id=HashId.decode(survey_id) #Uncomment on Production # survey_id="IamASurveyId" lol= DataSort(survey_id,uuid,aggregate) all_survey= lol.get_survey() if "referenced" in all_survey[0]: # return "reference" parent_survey= all_survey[0]['referenced']['$oid'] # parent_survey= HashId.decode(parent_survey) s= DataSort(parent_survey,uuid,aggregate) survey_data= s.get_uuid_label() else: survey_data= lol.get_uuid_label() j_data= d(survey_data) #return j_data # Get Responses for a cid response_data= lol.get_data() #return j_data['field_options']['options'][0]['label'] # Options try: options=[] option_code={} for i in range(len(j_data['field_options']['options'])): options.append(j_data['field_options']['options'][i]['label']) option_code["a_"+str(i+1)]=j_data['field_options']['options'][i]['label'] except: return "error" #Response Count temp= [] for i in range(len(response_data)): temp.append(response_data[i]['responses'][uuid]) #eturn j_data['field_type'] options_count={} if j_data['field_type'] not in ["ranking","rating","group_rating"]: for i in temp: if i in options_count:pass else:options_count[i]= temp.count(i) elif j_data['field_type'] in ["ranking"]: for i in temp: aTempList= i.split("###") for j in aTempList: bTempList= j.split("##") l = bTempList[0] if l in options_count: options_count[l]= int(options_count[l])+len(aTempList)-int(bTempList[1]) else: options_count[l]=len(aTempList)-int(bTempList[1]) # elif j_data['field_type']=="rating": # for i in temp: # aTempList= i.split("###") #Check if this breaks the logic # for j in aTempList: # bTempList= j.split("##") # if j in options_count: # options_count[j]= int(options_count[j])+ int(bTempList[1]) # else: # options_count[j]= int(bTempList[1]) elif j_data['field_type']=="group_rating": for i in temp: aTempList= i.split("###") #options_count={} for j in aTempList: bTempList= j.split("##") l = bTempList[0] #o_c= {a_1:} k= bTempList[1] if l in options_count: if k in options_count[l]: options_count[l][k]+=1 else: options_count[l][k]=1 else: options_count[l]={} options_count[l][k]=1 elif j_data['field_type']=="rating": for i in temp: if str(i) in options_count: options_count[str(i)] +=1 else: options_count[str(i)]=1 # if int(i)>6: # if "above_5" in options_count: # options_count["above_5"]= options_count["above_5"]+1 # else: # options_count["above_5"]=1 # elif int(i)<6 and int(i)>3 : # if "above_3" in options_count: # options_count["above_3"]= options_count["above_3"]+1 # else: # options_count["above_3"]=1 # elif int(i)<=3: # if "below_3" in options_count: # options_count["below_3"]= options_count["below_3"]+1 # else: # options_count["below_3"]=1 # elif j_data['field_type']=="short_text": # return "lol" response= {} if j_data['field_type']=="rating": avg= 0 for i in temp: avg= avg + int(i) response['avg_rating']= round(float(avg)/float(len(temp))) if j_data['field_type']=="group_rating": avg={} for key in options_count: counter=0 for bkey in options_count[key]: if int(bkey)!=0: counter+= float(bkey) * options_count[key][bkey] else: pass avg[key]= round(float(counter)/len(temp),2) # avg[key]=float(sum(options_count[key].values()))/float(len(temp)) response['avg_rating']=avg response['cid']= uuid # survey_id= j_data['survey_id'] response['survey_id']=survey_id response['label']=j_data['label'] response['type']=j_data['field_type'] response['option_code']=option_code response['option_count']=options_count #return option_code response['total_resp']=len(temp) response['garbage']= temp return d(response)