def new_task(project_id): """Return a new task for a project.""" # Check if the request has an arg: try: tasks = _retrieve_new_task(project_id) if type(tasks) is Response: return tasks # If there is a task for the user, return it if tasks is not None: guard = ContributionsGuard(sentinel.master) for task in tasks: guard.stamp(task, get_user_id_or_ip()) data = [task.dictize() for task in tasks] if len(data) == 0: response = make_response(json.dumps({})) elif len(data) == 1: response = make_response(json.dumps(data[0])) else: response = make_response(json.dumps(data)) response.mimetype = "application/json" return response return Response(json.dumps({}), mimetype="application/json") except Exception as e: print(e) return error.format_exception(e, target='project', action='GET')
def edit_question(short_name): (project, owner, n_tasks, n_task_runs, overall_progress, last_activity, n_results) = project_by_shortname(short_name) pro=pro_features() project_button = add_custom_contrib_button_to(project, get_user_id_or_ip()) feature_handler = ProFeatureHandler(current_app.config.get('PRO_FEATURES')) autoimporter_enabled = feature_handler.autoimporter_enabled_for(current_user) project_sanitized, owner_sanitized = sanitize_project_owner(project_button, owner, current_user) print project_button["contrib_button"] if "importer_type" in project.info.keys(): if(project.info["importer_type"]=="frg"): if(project_button["contrib_button"]=="draft"): if("questionSet" in project.info.keys()): session["edit_question_list"]=[] session["edit_question"]={"images":[],"documents":[],"videos":[],"audios":[]} for i in ["images","documents","videos","audios"]: if(len(project.info["questionSet"][i])>0): session["edit_question_list"].append(i) p=edit_draft_question(project) print "see"+p if(p!="-1"): return redirect_content_type(url_for('.'+p+"_edit",short_name=short_name)) else: return "-1" #return render_template('select_type.html',project=project_sanitized,pro_features=pro) else: return ("Sorry, You Edit the questions for draft project only.","alert") return "Sorry , You did not imported questions from Fundamenta Research"
def edit_question(short_name): (project, owner, n_tasks, n_task_runs, overall_progress, last_activity, n_results) = project_by_shortname(short_name) pro = pro_features() project_button = add_custom_contrib_button_to(project, get_user_id_or_ip()) feature_handler = ProFeatureHandler(current_app.config.get('PRO_FEATURES')) autoimporter_enabled = feature_handler.autoimporter_enabled_for( current_user) project_sanitized, owner_sanitized = sanitize_project_owner( project_button, owner, current_user) print project_button["contrib_button"] if (project_button["contrib_button"] == "draft"): if ("questionSet" not in project.info.keys()): project.info.update({ "questionSet": { "images": [], "videos": [], "audios": [], "documents": [] } }) project_repo.update(project) session["edit_question"] = { "images": [], "documents": [], "videos": [], "audios": [] } return redirect_content_type( url_for('.images_edit', short_name=short_name)) else: return ("Sorry, You Edit the questions for draft project only.", "alert")
def _filter_query(self, repo_info, limit, offset, orderby): filters = {} for k in request.args.keys(): if k not in ['limit', 'offset', 'api_key', 'last_id', 'all', 'fulltextsearch', 'desc', 'orderby', 'related', 'participated', 'full']: # Raise an error if the k arg is not a column if self.__class__ == Task and k == 'external_uid': pass else: getattr(self.__class__, k) filters[k] = request.args[k] repo = repo_info['repo'] filters = self.api_context(all_arg=request.args.get('all'), **filters) query_func = repo_info['filter'] filters = self._custom_filter(filters) last_id = request.args.get('last_id') if request.args.get('participated'): filters['participated'] = get_user_id_or_ip() fulltextsearch = request.args.get('fulltextsearch') desc = request.args.get('desc') if request.args.get('desc') else False desc = fuzzyboolean(desc) if last_id: results = getattr(repo, query_func)(limit=limit, last_id=last_id, fulltextsearch=fulltextsearch, desc=False, orderby=orderby, **filters) else: results = getattr(repo, query_func)(limit=limit, offset=offset, fulltextsearch=fulltextsearch, desc=desc, orderby=orderby, **filters) return results
def images(short_name): (project, owner, n_tasks, n_task_runs, overall_progress, last_activity, n_results) = project_by_shortname(short_name) pro=pro_features() project_button = add_custom_contrib_button_to(project, get_user_id_or_ip()) feature_handler = ProFeatureHandler(current_app.config.get('PRO_FEATURES')) autoimporter_enabled = feature_handler.autoimporter_enabled_for(current_user) project_sanitized, owner_sanitized = sanitize_project_owner(project_button, owner, current_user) if(session.get("question") is None): return redirect_content_type(url_for('.success',short_name=short_name)) if request.method == 'POST': type_q="normal" answer=[] if(request.form.get('question','')==""): flash("Atleast 1 question is required","warning") return render_template('images.html',project=project_sanitized, pro_features=pro) if(request.form.get('checkbox','')!=""): if(request.form.getlist('answer')[0]=="" or request.form.getlist('answer')[1]==""): flash("Atleast 2 answers are required","warning") return render_template('images.html',project=project_sanitized, pro_features=pro) else: type_q="mcqs" answer=request.form.getlist('answer') dictobj={"questionString":request.form.get('question'),"answers":answer,"type":type_q} session["question"]["images"].append(dictobj) if(request.form.get('submit','')=="submit"): p=draft_project(project) if(p!="-1"): return redirect_content_type(url_for('.'+p.lower(),short_name=short_name)) else: return redirect_content_type(url_for('.success',short_name=short_name)) return render_template('images.html',project=project_sanitized,pro_features=pro) #we are going to tags.html
def set_cache_presented_time(task_id, force=False): """Cache in Redis the initial datetime that a task was presented to a user. If force=True, cache will be updated if there is no key or an existing key. If force=False, cache will only be updated if no key exists. """ # usr can only be a registered user with a user_id usr = get_user_id_or_ip()['user_id'] or None redis_conn = sentinel.master # Timeout set for 60 minutes to coincide with inactivity timeout timeout = 60 * 60 # Only set cache if usr is not None so that the cache cannot be set # by calling the API directly if redis_conn is not None and usr is not None: presented_time = datetime.utcnow().isoformat() presented_time_key = 'pybossa:user:{0}:task_id:{1}:presented_time_key'.format(usr, task_id) # Set presented_time value if presented_time_key does not exist yet. # The presented time cannot be reset until it times out. # This will eliminate the ability for someone to manipulate the presented time # to make it look like they spent less time on a task than they actually did. # Besides user manipulation, if guards against browser reloads and accidental logouts. # This is an appropriate solution since we do not have complete information # regarding whether or not a user actually looked at a task before a browser reload, # logout or timeout. if redis_conn.get(presented_time_key) is None: redis_conn.setex(presented_time_key, timeout, presented_time) # Only overwrite an existing presented_time_value if force = True. # This should ONLY be used if there is no way for a user to take advantage # of this feature to manuipulate the presented time. elif force == True: redis_conn.setex(presented_time_key, timeout, presented_time)
def create_quiz(short_name): (project, owner, n_tasks, n_task_runs, overall_progress, last_activity, n_results) = project_by_shortname(short_name) project_id = project.id project_button = add_custom_contrib_button_to(project, get_user_id_or_ip()) feature_handler = ProFeatureHandler(current_app.config.get('PRO_FEATURES')) autoimporter_enabled = feature_handler.autoimporter_enabled_for( current_user) project_sanitized, owner_sanitized = sanitize_project_owner( project_button, owner, current_user) form = Add_quiz() if request.method == "POST" and form.validate(): quiz_name = form.name.data q = quiz(name=quiz_name, project_id=project_id) db.session.add(q) db.session.commit() project.info.update({"is_quiz_provided": True}) project_repo.update(project) session['quiz_name'] = quiz_name session['quiz_id'] = models.quiz.query.filter_by( name=quiz_name, project_id=project_id).first().quiz_id flash("Sucessfully created quiz", "success") return redirect(url_for('quiz.quiz_form', short_name=short_name)) return render_template("add_quiz.html", title="create quiz", form=form, project=project_sanitized, pro_features=pro_features())
def new_task(project_id): """Return a new task for a project.""" # Check if the request has an arg: try: tasks = _retrieve_new_task(project_id) if type(tasks) is Response: return tasks # If there is a task for the user, return it if tasks is not None: guard = ContributionsGuard(sentinel.master) for task in tasks: guard.stamp(task, get_user_id_or_ip()) data = [task.dictize() for task in tasks] if len(data) == 0: response = make_response(json.dumps({})) elif len(data) == 1: response = make_response(json.dumps(data[0])) else: response = make_response(json.dumps(data)) response.mimetype = "application/json" return response return Response(json.dumps({}), mimetype="application/json") except Exception as e: return error.format_exception(e, target='project', action='GET')
def _check_task_requested_by_user(taskrun, redis_conn): user_id_ip = get_user_id_or_ip() usr = user_id_ip['user_id'] or user_id_ip['user_ip'] key = 'pybossa:task_requested:user:%s:task:%s' % (usr, taskrun.task_id) task_requested = bool(redis_conn.get(key)) if user_id_ip['user_id'] is not None: redis_conn.delete(key) return task_requested
def _verify_auth(self, item): if not current_user.is_authenticated(): return False if current_user.admin or current_user.subadmin: return True project = Project(**get_project_data(item.project_id)) pwd_manager = get_pwd_manager(project) return not pwd_manager.password_needed(project, get_user_id_or_ip())
def _update_object(self, taskrun): """Update task_run object with user id or ip.""" self.check_can_post(taskrun.project_id, taskrun.task_id, get_user_id_or_ip()) task = task_repo.get_task(taskrun.task_id) guard = ContributionsGuard(sentinel.master) self._validate_project_and_task(taskrun, task) self._ensure_task_was_requested(task, guard) self._add_user_info(taskrun) self._add_created_timestamp(taskrun, task, guard)
def import_healthsites_tasks(short_name): project, owner, ps = project_by_shortname(short_name) ensure_authorized_to('read', project) ensure_authorized_to('update', project) title = project_title(project, "Import Tasks") loading_text = gettext("Importing tasks, this may take a while, wait...") pro = pro_features() dict_project = add_custom_contrib_button_to(project, get_user_id_or_ip(), ps=ps) project_sanitized, owner_sanitized = sanitize_project_owner( dict_project, owner, current_user, ps) template_args = dict( title=title, loading_text=loading_text, project=project_sanitized, owner=owner_sanitized, n_tasks=ps.n_tasks, overall_progress=ps.overall_progress, n_volunteers=ps.n_volunteers, n_completed_tasks=ps.n_completed_tasks, target='healthsites_importer.import_healthsites_tasks', pro_features=pro) importer_type = "healthsites" all_importers = importer.get_all_importer_names() if importer_type is not None and importer_type not in all_importers: return abort(404) form = BulkTaskHealthsitesImportForm(request.body) template_args['form'] = form if request.method == 'POST': if form.validate(): # pragma: no cover try: return _import_tasks(project, **form.get_import_data()) except BulkImportException as err_msg: raise flash(err_msg, 'error') except Exception as inst: # pragma: no cover raise current_app.logger.error(inst) msg = 'Oops! Looks like there was an error!' flash(gettext(msg), 'error') template_args[ 'template'] = '/projects/importers/%s.html' % importer_type return handle_content_type(template_args) if request.method == 'GET': template_args[ 'template'] = '/projects/importers/%s.html' % importer_type return handle_content_type(template_args)
def edit_success(short_name): (project, owner, n_tasks, n_task_runs, overall_progress, last_activity, n_results) = project_by_shortname(short_name) pro=pro_features() project_button = add_custom_contrib_button_to(project, get_user_id_or_ip()) feature_handler = ProFeatureHandler(current_app.config.get('PRO_FEATURES')) autoimporter_enabled = feature_handler.autoimporter_enabled_for(current_user) project_sanitized, owner_sanitized = sanitize_project_owner(project_button, owner, current_user) return render_template('edit_success.html',project=project_sanitized, pro_features=pro) #we are going to tags.html
def audios_edit(short_name): (project, owner, n_tasks, n_task_runs, overall_progress, last_activity, n_results) = project_by_shortname(short_name) pro=pro_features() project_button = add_custom_contrib_button_to(project, get_user_id_or_ip()) feature_handler = ProFeatureHandler(current_app.config.get('PRO_FEATURES')) autoimporter_enabled = feature_handler.autoimporter_enabled_for(current_user) project_sanitized, owner_sanitized = sanitize_project_owner(project_button, owner, current_user) if request.method == 'POST': session_count=len(session["edit_question"]["audios"]); session["edit_question"]["audios"]=[] for j in range(1,session_count+1): ans=[] type_q="normal" print str(j)+'_question' if(request.form.get(str(j)+'_question','')!=""): que=request.form.get(str(j)+'_question') if(request.form.get(str(j)+'_divcheckbox','')!=""): type_q="mcqs" if(request.form.get(str(j)+'_answer','')!=""): ans=request.form.getlist(str(j)+'_answer') dictobj={"questionString":request.form.get(str(j)+'_question'),"answers":ans,"type":type_q} session["edit_question"]["audios"].append(dictobj) if(request.form.get('submit','')=="submit"): p=edit_draft_question(project) project.info["questionSet"]["audios"]=session["edit_question"]["audios"] project_repo.update(project) if(p!="-1"): return redirect_content_type(url_for('.'+p.lower()+"_edit",short_name=short_name)) else: return redirect_content_type(url_for('.edit_success',short_name=short_name)) else: type_q="normal" answer=[] if(request.form.get('question','')==""): flash("Question field is Empty","warning") return render_template('audios_edit.html',project=project_sanitized, pro_features=pro) if(request.form.get('checkbox','')!=""): if(request.form.getlist('answer')[0]=="" or request.form.getlist('answer')[1]==""): flash("Atleast 2 answers are required","warning") return render_template('audios_edit.html',project=project_sanitized, pro_features=pro) else: type_q="mcqs" answer=request.form.getlist('answer') dictobj={"questionString":request.form.get('question'),"answers":answer,"type":type_q} session["edit_question"]["audios"].append(dictobj) return render_template('audios_edit.html',project=project_sanitized,pro_features=pro) #we are going to tags.html
def _add_timestamps(self, taskrun, task, guard): finish_time = datetime.utcnow().isoformat() # /cachePresentedTime API only caches when there is a user_id # otherwise it returns an arbitrary valid timestamp so that answer can be submitted if guard.retrieve_presented_timestamp(task, get_user_id_or_ip()): created = self._validate_datetime( guard.retrieve_presented_timestamp(task, get_user_id_or_ip())) else: created = datetime.strptime(self.DEFAULT_DATETIME, self.DATETIME_FORMAT).isoformat() # sanity check if created < finish_time: taskrun.created = created taskrun.finish_time = finish_time else: # return an arbitrary valid timestamp so that answer can be submitted created = datetime.strptime(self.DEFAULT_DATETIME, self.DATETIME_FORMAT) taskrun.created = created.isoformat() taskrun.finish_time = finish_time
def validation(page=1): """Manage validations.""" # response = dict(template='admin/validation.html', # title=gettext("Manage validations"), # csrf=generate_csrf()) # return handle_content_type(response) project, owner, ps = project_by_shortname("frd") title = project_title(project, "Tasks") pro = pro_features() def respond(): per_page = 100 offset = (page - 1) * per_page count = ps.n_tasks page_tasks = cached_projects.browse_tasks_validation(project.get('id'), per_page, offset, min_n_answers=3) pagination = Pagination(page, per_page, count) project_sanitized, owner_sanitized = sanitize_project_owner( project, owner, current_user, ps) data = dict(template='admin/validation.html', project=project_sanitized, owner=owner_sanitized, tasks=page_tasks, title=title, pagination=pagination, n_tasks=ps.n_tasks, overall_progress=ps.overall_progress, n_volunteers=ps.n_volunteers, n_completed_tasks=ps.n_completed_tasks, pro_features=pro) return handle_content_type(data) if project.needs_password(): redirect_to_password = _check_if_redirect_to_password(project) if redirect_to_password: return redirect_to_password else: ensure_authorized_to('read', project) zip_enabled(project, current_user) project = add_custom_contrib_button_to(project, get_user_id_or_ip()) return respond()
def new_task(project_id): """Return a new task for a project.""" # Check if the request has an arg: try: task = _retrieve_new_task(project_id) # If there is a task for the user, return it if task is not None: guard = ContributionsGuard(sentinel.master) guard.stamp(task, get_user_id_or_ip()) response = make_response(json.dumps(task.dictize())) response.mimetype = "application/json" return response return Response(json.dumps({}), mimetype="application/json") except Exception as e: return error.format_exception(e, target='project', action='GET')
def new_task(project_id): """Return a new task for a project.""" # Check if the request has an arg: try: tasks, timeout = _retrieve_new_task_with_timeout(project_id) if type(tasks) is Response: return tasks # If there is a task for the user, return it if tasks is not None: guard = ContributionsGuard(sentinel.master, timeout=timeout) for task in tasks: guard.stamp(task, get_user_id_or_ip()) if not guard.check_task_presented_timestamp( task, get_user_id_or_ip()): guard.stamp_presented_time(task, get_user_id_or_ip()) else: # user returning back for the same task # original presented time has not expired yet # to continue original presented time, extend expiry guard.extend_task_presented_timestamp_expiry( task, get_user_id_or_ip()) data = [task.dictize() for task in tasks] if len(data) == 0: response = make_response(json.dumps({})) elif len(data) == 1: response = make_response(json.dumps(data[0])) else: response = make_response(json.dumps(data)) response.mimetype = "application/json" return response return Response(json.dumps({}), mimetype="application/json") except Exception as e: return error.format_exception(e, target='project', action='GET')
def success(short_name): (project, owner, n_tasks, n_task_runs, overall_progress, last_activity, n_results) = project_by_shortname(short_name) pro=pro_features() add_task(project) global previous_data previous_data=[] project_button = add_custom_contrib_button_to(project, get_user_id_or_ip()) feature_handler = ProFeatureHandler(current_app.config.get('PRO_FEATURES')) autoimporter_enabled = feature_handler.autoimporter_enabled_for(current_user) project_sanitized, owner_sanitized = sanitize_project_owner(project_button, owner, current_user) flash("Your Tasks Uploded Successfully","success") #return render_template('success.html',project=project_sanitized,pro_features=pro) #we are going to tags.html if(not is_quiz_provided(project.id)): return redirect(url_for('quiz.create_quiz',short_name=short_name)) else: return redirect(url_for('project.details',short_name=short_name))
def upload_task(short_name): (project, owner, n_tasks, n_task_runs, overall_progress, last_activity, n_results) = project_by_shortname(short_name) pro=pro_features() project_button = add_custom_contrib_button_to(project, get_user_id_or_ip()) feature_handler = ProFeatureHandler(current_app.config.get('PRO_FEATURES')) autoimporter_enabled = feature_handler.autoimporter_enabled_for(current_user) project_sanitized, owner_sanitized = sanitize_project_owner(project_button, owner, current_user) if request.method=='POST': upload_form=TaskUpload() if upload_form.validate_on_submit(): _file=request.files['avatar'] #extract_files_local(parent_path+"/uploads"+CONTAINER,_file.filename) if _file and allowed_file(_file.filename): _file.save(os.path.join((parent_path+'/uploads/'+CONTAINER) , _file.filename)) if(check_file_size(parent_path+'/uploads/'+CONTAINER+"/"+_file.filename)): global zipobj zipobj=extract_files_local((parent_path+"/uploads/"+CONTAINER),_file.filename,project.id) session["zzz"]=zipobj["zzz"] zipobj.pop("zzz",None) if "directory_names" not in project.info.keys(): project.info.update({"directory_names":[]}) project.info["directory_names"].append(session["zzz"]) project_repo.update(project) #add_task(project.id,zipobj["zzz"]) return redirect_content_type(url_for('.select_type', short_name=short_name)) else: if os.path.exists(parent_path+'/uploads/'+CONTAINER+"/"+_file.filename): os.remove(parent_path+'/uploads/'+CONTAINER+"/"+_file.filename) flash('File Size should be less than 5 MB'); else: flash(gettext('Please upload the file'),'warning') upload_form =TaskUpload() response =dict(template='/upload_form.html', upload_form=upload_form, project=project_sanitized, pro_features=pro ) return handle_content_type(response)
def select_type(short_name): (project, owner, n_tasks, n_task_runs, overall_progress, last_activity, n_results) = project_by_shortname(short_name) pro=pro_features() project_button = add_custom_contrib_button_to(project, get_user_id_or_ip()) feature_handler = ProFeatureHandler(current_app.config.get('PRO_FEATURES')) autoimporter_enabled = feature_handler.autoimporter_enabled_for(current_user) project_sanitized, owner_sanitized = sanitize_project_owner(project_button, owner, current_user) print short_name global zipobj li=["Images","Videos",'Audios','Documents'] #classification files if request.method == 'POST': global list_container list_container=request.form.getlist('selecttype') #selected classification list for i in li: if i not in list_container: n=session["zzz"]#this is parent path of the folder which were unchecked by user if os.path.exists(n+"/"+i.lower()): shutil.rmtree(n+"/"+i.lower()) #deletion of folder if(len(list_container)==0): flash("You must select atleast one file","danger") return render_template('select_type.html',arr=zipobj,project=project_sanitized,pro_features=pro) print "Going to function" global previous_data p=draft_project(project) if(len(previous_data)!=0): l=" , ".join(previous_data) print l flash(l+" questions are already uploaded","info") if(p!="-1"): return redirect_content_type(url_for('.'+p.lower(),short_name=short_name)) else: return redirect_content_type(url_for('.success',short_name=short_name)) return render_template('select_type.html',arr=zipobj,project=project_sanitized, pro_features=pro) #sending the classified information to the select_type.html
def mark_task_as_requested_by_user(task, redis_conn): usr = get_user_id_or_ip()['user_id'] or get_user_id_or_ip()['user_ip'] key = 'pybossa:task_requested:user:%s:task:%s' % (usr, task.id) timeout = 60 * 60 redis_conn.setex(key, timeout, True)
def _retrieve_new_task(project_id): project = project_repo.get(project_id) if project is None or not (project.published or current_user.admin or current_user.id in project.owners_ids): raise NotFound if current_user.is_anonymous: info = dict(error="This project does not allow anonymous contributors") error = [model.task.Task(info=info)] return error, None, lambda x: x if current_user.get_quiz_failed(project): # User is blocked from project so don't return a task return None, None, None # check cookie pwd_manager = get_pwd_manager(project) user_id_or_ip = get_user_id_or_ip() if pwd_manager.password_needed(project, user_id_or_ip): raise Forbidden("No project password provided") if request.args.get('external_uid'): resp = jwt_authorize_project(project, request.headers.get('Authorization')) if resp != True: return resp, lambda x: x if request.args.get('limit'): limit = int(request.args.get('limit')) else: limit = 1 if limit > 100: limit = 100 if request.args.get('offset'): offset = int(request.args.get('offset')) else: offset = 0 if request.args.get('orderby'): orderby = request.args.get('orderby') else: orderby = 'id' if request.args.get('desc'): desc = fuzzyboolean(request.args.get('desc')) else: desc = False user_id = None if current_user.is_anonymous else current_user.id user_ip = (anonymizer.ip(request.remote_addr or '127.0.0.1') if current_user.is_anonymous else None) external_uid = request.args.get('external_uid') sched_rand_within_priority = project.info.get('sched_rand_within_priority', False) user = user_repo.get(user_id) if (user.get_quiz_not_started(project) and user.get_quiz_enabled(project) and not task_repo.get_user_has_task_run_for_project( project_id, user_id)): user.set_quiz_status(project, 'in_progress') user_repo.update(user) task = sched.new_task(project.id, project.info.get('sched'), user_id, user_ip, external_uid, offset, limit, orderby=orderby, desc=desc, rand_within_priority=sched_rand_within_priority, gold_only=user.get_quiz_in_progress(project)) handler = partial(pwd_manager.update_response, project=project, user=user_id_or_ip) return task, project.info.get('timeout'), handler
def quiz_form(short_name): (project, owner, n_tasks, n_task_runs, overall_progress, last_activity, n_results) = project_by_shortname(short_name) form = Create_quiz() # Fetch appropriate form from forms.py project_button = add_custom_contrib_button_to(project, get_user_id_or_ip()) feature_handler = ProFeatureHandler(current_app.config.get('PRO_FEATURES')) autoimporter_enabled = feature_handler.autoimporter_enabled_for( current_user) project_sanitized, owner_sanitized = sanitize_project_owner( project_button, owner, current_user) if request.method == "POST" and form.validate(): #collecting data from forms.py que = form.question_text.data #collect the entered question text _file = request.files['file_field'] if _file and allowed_file(_file.filename): parent_path = current_app.root_path[:current_app.root_path. rfind("/")] _file.save( os.path.join((parent_path + '/uploads/' + CONTAINER), _file.filename)) file_path = '/uploads/' + CONTAINER + '/' + _file.filename option_A = form.oA.data #collect entered option A text option_B = form.oB.data #collect entered option B text option_C = form.oC.data #collect entered option C text option_D = form.oD.data #collect entered option D text correct_answer = form.correct_answer.data #collect entered correct answer # Based on entered answer, store the option text in the answer field in the database if correct_answer == 'A': correct_answer = option_A elif correct_answer == 'B': correct_answer = option_B elif correct_answer == 'C': correct_answer = option_C elif correct_answer == 'D': correct_answer = option_D category = form.category.data #collect entered question category q = question(quiz_id=session['quiz_id'], q_text=que, file_path=file_path, option1=option_A, option2=option_B, option3=option_C, option4=option_D, answer=correct_answer, category=category ) # Create object of class question from questions.py db.session.add(q) # Add object q to db.session db.session.commit() # Commit changes to app.db if request.form['submit'] == 'ADD': return redirect(url_for('quiz.quiz_form', short_name=short_name)) elif request.form['submit'] == 'SUBMIT': flash("Sucessfully added questions to " + session['quiz_name'], "success") return redirect(url_for('project.details', short_name=short_name)) return render_template("create_quiz.html", title="Add Question", quiz_name=session['quiz_name'], form=form, project=project_sanitized, pro_features=pro_features()) # Render form template
def check_can_post(self, project_id, task_id): if not can_post(project_id, task_id, get_user_id_or_ip()): raise Forbidden("You must request a task first!")
def _retrieve_new_task(project_id): project = project_repo.get(project_id) if project is None: raise NotFound if current_user.is_anonymous(): info = dict(error="This project does not allow anonymous contributors") error = [model.task.Task(info=info)] return error, None, lambda x: x # check cookie pwd_manager = get_pwd_manager(project) user_id_or_ip = get_user_id_or_ip() if pwd_manager.password_needed(project, user_id_or_ip): raise Forbidden("No project password provided") if request.args.get('external_uid'): resp = jwt_authorize_project(project, request.headers.get('Authorization')) if resp != True: return resp, lambda x: x if request.args.get('limit'): limit = int(request.args.get('limit')) else: limit = 1 if limit > 100: limit = 100 if request.args.get('offset'): offset = int(request.args.get('offset')) else: offset = 0 if request.args.get('orderby'): orderby = request.args.get('orderby') else: orderby = 'id' if request.args.get('desc'): desc = fuzzyboolean(request.args.get('desc')) else: desc = False user_id = None if current_user.is_anonymous() else current_user.id user_ip = (anonymizer.ip(request.remote_addr or '127.0.0.1') if current_user.is_anonymous() else None) external_uid = request.args.get('external_uid') sched_rand_within_priority = project.info.get('sched_rand_within_priority', False) task = sched.new_task(project.id, project.info.get('sched'), user_id, user_ip, external_uid, offset, limit, orderby=orderby, desc=desc, rand_within_priority=sched_rand_within_priority) handler = partial(pwd_manager.update_response, project=project, user=user_id_or_ip) return task, project.info.get('timeout'), handler
def _add_created_timestamp(self, taskrun, task, guard): taskrun.created = guard.retrieve_timestamp(task, get_user_id_or_ip()) guard._remove_task_stamped(task, get_user_id_or_ip())
def _ensure_task_was_requested(self, task, guard): if not guard.check_task_stamped(task, get_user_id_or_ip()): raise Forbidden('You must request a task first!')
def _add_created_timestamp(self, taskrun, task, guard): taskrun.created = guard.retrieve_timestamp(task, get_user_id_or_ip())
def _retrieve_new_task(project_id): project = project_repo.get(project_id) if project is None or not (project.published or current_user.admin or current_user.id in project.owners_ids): raise NotFound if current_user.is_anonymous: info = dict(error="This project does not allow anonymous contributors") error = [model.task.Task(info=info)] return error, None, lambda x: x if current_user.get_quiz_failed(project): # User is blocked from project so don't return a task return None, None, None # check cookie pwd_manager = get_pwd_manager(project) user_id_or_ip = get_user_id_or_ip() if pwd_manager.password_needed(project, user_id_or_ip): raise Forbidden("No project password provided") if request.args.get('external_uid'): resp = jwt_authorize_project(project, request.headers.get('Authorization')) if resp != True: return resp, lambda x: x if request.args.get('limit'): limit = int(request.args.get('limit')) else: limit = 1 if limit > 100: limit = 100 if request.args.get('offset'): offset = int(request.args.get('offset')) else: offset = 0 if request.args.get('orderby'): orderby = request.args.get('orderby') else: orderby = 'id' if request.args.get('desc'): desc = fuzzyboolean(request.args.get('desc')) else: desc = False user_id = None if current_user.is_anonymous else current_user.id user_ip = (anonymizer.ip(request.remote_addr or '127.0.0.1') if current_user.is_anonymous else None) external_uid = request.args.get('external_uid') sched_rand_within_priority = project.info.get('sched_rand_within_priority', False) user = user_repo.get(user_id) if (project.published and user_id != project.owner_id and user_id not in project.owners_ids and user.get_quiz_not_started(project) and user.get_quiz_enabled(project) and not task_repo.get_user_has_task_run_for_project( project_id, user_id)): user.set_quiz_status(project, 'in_progress') # We always update the user even if we didn't change the quiz status. # The reason for that is the user.<?quiz?> methods take a snapshot of the project's quiz # config the first time it is accessed for a user and save that snapshot # with the user. So we want to commit that snapshot if this is the first access. user_repo.update(user) # Allow scheduling a gold-only task if quiz mode is enabled for the user and the project. quiz_mode_enabled = user.get_quiz_in_progress( project) and project.info["quiz"]["enabled"] task = sched.new_task(project.id, project.info.get('sched'), user_id, user_ip, external_uid, offset, limit, orderby=orderby, desc=desc, rand_within_priority=sched_rand_within_priority, gold_only=quiz_mode_enabled) handler = partial(pwd_manager.update_response, project=project, user=user_id_or_ip) return task, project.info.get('timeout'), handler