INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Callback for self._client.new_job
def _callback(self, bjobid, result, grade, problems, tests, custom, archive, stdout, stderr): """ Callback for self._client.new_job """ self._jobs_done[str(bjobid)] = (result, grade, problems, tests, custom, archive, stdout, stderr) self._waiting_jobs.remove(str(bjobid))
Get the result of task. Must only be called ONCE, AFTER the task is done (after a successfull call to is_done). :return a tuple (result, grade, problems, tests, custom, archive) result is itself a tuple containing the result string and the main feedback (i.e. ('success', 'You succeeded') ...
def get_result(self, bjobid): """ Get the result of task. Must only be called ONCE, AFTER the task is done (after a successfull call to is_done). :return a tuple (result, grade, problems, tests, custom, archive) result is itself a tuple containing the result string and the ma...
GET request
def POST_AUTH(self, courseid): # pylint: disable=arguments-differ """ GET request """ course, __ = self.get_course_and_check_rights(courseid) user_input = web.input(tasks=[], aggregations=[], users=[]) if "filter_type" not in user_input or "type" not in user_input or "format" not in u...
GET request
def GET_AUTH(self, courseid): # pylint: disable=arguments-differ """ GET request """ course, __ = self.get_course_and_check_rights(courseid) user_input = web.input() # First, check for a particular submission if "submission" in user_input: submission = self.database...
Allow to connect through a LDAP service Available configuration: :: plugins: - plugin_module": "inginious.frontend.plugins.auth.ldap_auth", host: "ldap.test.be", port: 0, encryption: "ssl", base_dn: "o...
def init(plugin_manager, _, _2, conf): """ Allow to connect through a LDAP service Available configuration: :: plugins: - plugin_module": "inginious.frontend.plugins.auth.ldap_auth", host: "ldap.test.be", port: 0, ...
>>> from re import compile >>> atomics = (True, 1, 1.0, '', None, compile(''), datetime.now(), b'') >>> any(needs_encode(i) for i in atomics) False >>> needs_encode([1, 2, 3]) False >>> needs_encode([]) False >>> needs_encode([1, [2, 3]]) False >>> needs_encode({}) False ...
def needs_encode(obj): ''' >>> from re import compile >>> atomics = (True, 1, 1.0, '', None, compile(''), datetime.now(), b'') >>> any(needs_encode(i) for i in atomics) False >>> needs_encode([1, 2, 3]) False >>> needs_encode([]) False >>> needs_encode([1, [2, 3]]) False ...
Removes all sessions older than ``timeout`` seconds. Called automatically on every session access.
def cleanup(self, timeout): ''' Removes all sessions older than ``timeout`` seconds. Called automatically on every session access. ''' cutoff = time() - timeout self.collection.remove({_atime: {'$lt': cutoff}})
Loads the plugin manager. Must be done after the initialisation of the client
def load(self, client, webpy_app, course_factory, task_factory, database, user_manager, submission_manager, config): """ Loads the plugin manager. Must be done after the initialisation of the client """ self._app = webpy_app self._task_factory = task_factory self._database = database ...
Add a new page to the web application. Only available after that the Plugin Manager is loaded
def add_page(self, pattern, classname): """ Add a new page to the web application. Only available after that the Plugin Manager is loaded """ if not self._loaded: raise PluginManagerNotLoadedException() self._app.add_mapping(pattern, classname)
Add a task file manager. Only available after that the Plugin Manager is loaded
def add_task_file_manager(self, task_file_manager): """ Add a task file manager. Only available after that the Plugin Manager is loaded """ if not self._loaded: raise PluginManagerNotLoadedException() self._task_factory.add_custom_task_file_manager(task_file_manager)
Register a new authentication method name the name of the authentication method, typically displayed by the webapp input_to_display Only available after that the Plugin Manager is loaded
def register_auth_method(self, auth_method): """ Register a new authentication method name the name of the authentication method, typically displayed by the webapp input_to_display Only available after that the Plugin Manager is loaded "...
Create a zip file containing all information about a given course in database and then remove it from db
def dump_course(self, courseid): """ Create a zip file containing all information about a given course in database and then remove it from db""" filepath = os.path.join(self.backup_dir, courseid, datetime.datetime.now().strftime("%Y%m%d.%H%M%S") + ".zip") if not os.path.exists(os.path.dirname(f...
Restores a course of given courseid to a date specified in backup (format : YYYYMMDD.HHMMSS)
def restore_course(self, courseid, backup): """ Restores a course of given courseid to a date specified in backup (format : YYYYMMDD.HHMMSS) """ self.wipe_course(courseid) filepath = os.path.join(self.backup_dir, courseid, backup + ".zip") with zipfile.ZipFile(filepath, "r") as zipf: ...
Erase all course data
def delete_course(self, courseid): """ Erase all course data """ # Wipes the course (delete database) self.wipe_course(courseid) # Deletes the course from the factory (entire folder) self.course_factory.delete_course(courseid) # Removes backup filepath = os.path...
GET request
def GET_AUTH(self, courseid): # pylint: disable=arguments-differ """ GET request """ course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=False) data = web.input() if "download" in data: filepath = os.path.join(self.backup_dir, courseid, data["download"]...
POST request
def POST_AUTH(self, courseid): # pylint: disable=arguments-differ """ POST request """ course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=False) msg = "" error = False data = web.input() if not data.get("token", "") == self.user_manager.session_tok...
Get all data and display the page
def page(self, course, msg="", error=False): """ Get all data and display the page """ thehash = hashlib.sha512(str(random.getrandbits(256)).encode("utf-8")).hexdigest() self.user_manager.set_session_token(thehash) backups = self.get_backup_list(course) return self.template_hel...
Show BasicCodeProblem and derivatives
def show_input(self, template_helper, language, seed): """ Show BasicCodeProblem and derivatives """ header = ParsableText(self.gettext(language,self._header), "rst", translation=self._translations.get(language, gettext.NullTranslations())) return str(DisplayableCod...
Show InputBox
def show_input(self, template_helper, language, seed): """ Show InputBox """ header = ParsableText(self.gettext(language, self._header), "rst", translation=self._translations.get(language, gettext.NullTranslations())) return str(DisplayableCodeSingleLineProblem.get_...
Show FileBox
def show_input(self, template_helper, language, seed): """ Show FileBox """ header = ParsableText(self.gettext(language, self._header), "rst", translation=self._translations.get(language, gettext.NullTranslations())) return str(DisplayableFileProblem.get_renderer(te...
Show multiple choice problems
def show_input(self, template_helper, language, seed): """ Show multiple choice problems """ choices = [] limit = self._limit if limit == 0: limit = len(self._choices) # no limit rand = Random("{}#{}#{}".format(self.get_task().get_id(), self.get_id(), seed)) ...
Show MatchProblem
def show_input(self, template_helper, language, seed): """ Show MatchProblem """ header = ParsableText(self.gettext(language, self._header), "rst", translation=self._translations.get(language, gettext.NullTranslations())) return str(DisplayableMatchProblem.get_rende...
Set submission whose id is `submissionid` to selected grading submission for the given course/task. Returns a boolean indicating whether the operation was successful or not.
def set_selected_submission(self, course, task, submissionid): """ Set submission whose id is `submissionid` to selected grading submission for the given course/task. Returns a boolean indicating whether the operation was successful or not. """ submission = self.submission_manager.g...
GET request
def GET(self, courseid, taskid, isLTI): """ GET request """ username = self.user_manager.session_username() # Fetch the course try: course = self.course_factory.get_course(courseid) except exceptions.CourseNotFoundException as ex: raise web.notfound(str(e...
POST a new submission
def POST(self, courseid, taskid, isLTI): """ POST a new submission """ username = self.user_manager.session_username() course = self.course_factory.get_course(courseid) if not self.user_manager.course_is_open_to_user(course, username, isLTI): return self.template_helper.get_...
Converts a submission to json (keeps only needed fields)
def submission_to_json(self, task, data, debug, reloading=False, replace=False, tags={}): """ Converts a submission to json (keeps only needed fields) """ if "ssh_host" in data: return json.dumps({'status': "waiting", 'text': "<b>SSH server active</b>", 'ssh_h...
GET request
def GET(self, courseid, taskid, path): # pylint: disable=arguments-differ """ GET request """ try: course = self.course_factory.get_course(courseid) if not self.user_manager.course_is_open_to_user(course): return self.template_helper.get_renderer().course_unavail...
Add a job in the queue :param username: :param courseid: :param taskid: :param consumer_key: :param service_url: :param result_id:
def add(self, username, courseid, taskid, consumer_key, service_url, result_id): """ Add a job in the queue :param username: :param courseid: :param taskid: :param consumer_key: :param service_url: :param result_id: """ search = {"username": userna...
Increment the number of attempt for an entry and :param mongo_id: :return:
def _increment_attempt(self, mongo_id): """ Increment the number of attempt for an entry and :param mongo_id: :return: """ entry = self._database.lis_outcome_queue.find_one_and_update({"_id": mongo_id}, {"$inc": {"nb_attempt": 1}}) self._add_to_queue(entry)
Checks if user is authenticated and calls POST_AUTH or performs login and calls GET_AUTH. Otherwise, returns the login template.
def GET(self): """ Checks if user is authenticated and calls POST_AUTH or performs login and calls GET_AUTH. Otherwise, returns the login template. """ data = self.user_manager.session_lti_info() if data is None: raise web.notfound() try: ...
Verify and parse the data for the LTI basic launch
def _parse_lti_data(self, courseid, taskid): """ Verify and parse the data for the LTI basic launch """ post_input = web.webapi.rawinput("POST") self.logger.debug('_parse_lti_data:' + str(post_input)) try: course = self.course_factory.get_course(courseid) except exce...
Returns the most appropriate name to identify the user
def _find_realname(self, post_input): """ Returns the most appropriate name to identify the user """ # First, try the full name if "lis_person_name_full" in post_input: return post_input["lis_person_name_full"] if "lis_person_name_given" in post_input and "lis_person_name_fa...
GET request
def GET_AUTH(self): # pylint: disable=arguments-differ """ GET request """ auth_methods = self.user_manager.get_auth_methods() user_data = self.database.users.find_one({"username": self.user_manager.session_username()}) bindings = user_data.get("bindings", {}) return self.templa...
POST request
def POST_AUTH(self): # pylint: disable=arguments-differ """ POST request """ msg = "" error = False user_data = self.database.users.find_one({"username": self.user_manager.session_username()}) if not user_data: raise web.notfound() user_input = web.input()...
Compute statistics about submissions and tags. This function returns a tuple of lists following the format describe below: ( [('Number of submissions', 13), ('Evaluation submissions', 2), …], [(<tag>, '61%', '50%'), (<tag>, '76%', '100%'), …] )
def compute_statistics(tasks, data, ponderation): """ Compute statistics about submissions and tags. This function returns a tuple of lists following the format describe below: ( [('Number of submissions', 13), ('Evaluation submissions', 2), …], [(<tag>, '61%', '50%'), (<tag>, '76%'...
Compute base statistics about submissions
def fast_stats(data): """ Compute base statistics about submissions """ total_submission = len(data) total_submission_best = 0 total_submission_best_succeeded = 0 for submission in data: if "best" in submission and submission["best"]: total_submission_best = total_s...
GET request
def GET_AUTH(self, courseid, f=None, t=None): # pylint: disable=arguments-differ """ GET request """ course, __ = self.get_course_and_check_rights(courseid) tasks = course.get_tasks() now = datetime.now().replace(minute=0, second=0, microsecond=0) error = None if f == N...
Register a type of message to be sent. After this message has been sent, if the answer is received, callback_recv is called. If the remote server becomes dones, calls callback_abrt. :param send_msg: class of message to be sent :param recv_msg: message that the server should send in resp...
def _register_transaction(self, send_msg, recv_msg, coroutine_recv, coroutine_abrt, get_key=None, inter_msg=None): """ Register a type of message to be sent. After this message has been sent, if the answer is received, callback_recv is called. If the remote server becomes dones, calls ca...
Create a transaction with the distant server :param msg: message to be sent :param args: args to be sent to the coroutines given to `register_transaction` :param kwargs: kwargs to be sent to the coroutines given to `register_transaction`
async def _create_transaction(self, msg, *args, **kwargs): """ Create a transaction with the distant server :param msg: message to be sent :param args: args to be sent to the coroutines given to `register_transaction` :param kwargs: kwargs to be sent to the coroutines given to `r...
Task that ensures Pings are sent periodically to the distant server :return:
async def _do_ping(self): """ Task that ensures Pings are sent periodically to the distant server :return: """ try: while True: await asyncio.sleep(1) if self._ping_count > 10: await self._reconnect() ...
Called when the remote server is innacessible and the connection has to be restarted
async def _reconnect(self): """ Called when the remote server is innacessible and the connection has to be restarted """ # 1. Close all transactions for msg_class in self._transactions: _1, _2, _3, coroutine_abrt, _4 = self._msgs_registered[msg_class] if ...
Starts the client
async def client_start(self): """ Starts the client """ await self._start_socket() await self._on_connect() self._ping_count = 0 # Start the loops, and don't forget to add them to the list of asyncio task to close when the client restarts task_socket = s...
GET request
def GET_AUTH(self, courseid): # pylint: disable=arguments-differ """ GET request """ course, _ = self.get_course_and_check_rights(courseid) return self.page(course)
Get all data and display the page
def page(self, course): """ Get all data and display the page """ if not self.webdav_host: raise web.notfound() url = self.webdav_host + "/" + course.get_id() username = self.user_manager.session_username() apikey = self.user_manager.session_api_key() return ...
Open existing feedback file
def load_feedback(): """ Open existing feedback file """ result = {} if os.path.exists(_feedback_file): f = open(_feedback_file, 'r') cont = f.read() f.close() else: cont = '{}' try: result = json.loads(cont) if cont else {} except ValueError as e: ...
Save feedback file
def save_feedback(rdict): """ Save feedback file """ # Check for output folder if not os.path.exists(_feedback_dir): os.makedirs(_feedback_dir) jcont = json.dumps(rdict) f = open(_feedback_file, 'w') f.write(jcont) f.close()
Set problem specific result value
def set_problem_result(result, problem_id): """ Set problem specific result value """ rdict = load_feedback() if not 'problems' in rdict: rdict['problems'] = {} cur_val = rdict['problems'].get(problem_id, '') rdict['problems'][problem_id] = [result, cur_val] if type(cur_val) == str else [res...
Set global feedback in case of error
def set_global_feedback(feedback, append=False): """ Set global feedback in case of error """ rdict = load_feedback() rdict['text'] = rdict.get('text', '') + feedback if append else feedback save_feedback(rdict)
Set problem specific feedback
def set_problem_feedback(feedback, problem_id, append=False): """ Set problem specific feedback """ rdict = load_feedback() if not 'problems' in rdict: rdict['problems'] = {} cur_val = rdict['problems'].get(problem_id, '') rdict['problems'][problem_id] = (cur_val + feedback if append else fe...
Set the tag 'tag' to the value True or False. :param value: should be a boolean :param tag: should be the id of the tag. Can not starts with '*auto-tag-'
def set_tag(tag, value): """ Set the tag 'tag' to the value True or False. :param value: should be a boolean :param tag: should be the id of the tag. Can not starts with '*auto-tag-' """ if not tag.startswith("*auto-tag-"): rdict = load_feedback() tests = rdict.setdefault("te...
Add a tag with generated id. :param value: everything working with the str() function
def tag(value): """ Add a tag with generated id. :param value: everything working with the str() function """ rdict = load_feedback() tests = rdict.setdefault("tests", {}) tests["*auto-tag-" + str(hash(str(value)))] = str(value) save_feedback(rdict)
Set a custom value to be given back in the feedback :param custom_name: name/key of the entry to be placed in the custom dict :param custom_val: content of the entry to be placed in the custom dict
def set_custom_value(custom_name, custom_val): """ Set a custom value to be given back in the feedback :param custom_name: name/key of the entry to be placed in the custom dict :param custom_val: content of the entry to be placed in the custom dict """ rdict = load_feedback() if not "custom"...
Parse a template, using the given parameters, and set it as the feedback message. tpl_name must indicate a file. Given that XX_XX is the lang code of the current user ('en_US' or 'fr_FR', for example), this function will search template file in different locations, in the following order: - [cu...
def set_feedback_from_tpl(tpl_name, parameters, problem_id=None, append=False): """ Parse a template, using the given parameters, and set it as the feedback message. tpl_name must indicate a file. Given that XX_XX is the lang code of the current user ('en_US' or 'fr_FR', for example), this function...
Displays a BIG warning
def _display_big_warning(self, content): """ Displays a BIG warning """ print("") print(BOLD + WARNING + "--- WARNING ---" + ENDC) print(WARNING + content + ENDC) print("")
Run the installator
def run(self): """ Run the installator """ self._display_header("BACKEND CONFIGURATION") options = {} while True: options = {} backend = self.ask_backend() if backend == "local": self._display_info("Backend chosen: local. Testing the co...
Ask some parameters about the local configuration
def _ask_local_config(self): """ Ask some parameters about the local configuration """ options = {"backend": "local", "local-config": {}} # Concurrency while True: concurrency = self._ask_with_default( "Maximum concurrency (number of tasks running simultaneou...
Ask the user to choose the backend
def ask_backend(self): """ Ask the user to choose the backend """ response = self._ask_boolean( "Do you have a local docker daemon (on Linux), do you use docker-machine via a local machine, or do you use " "Docker for macOS?", True) if (response): self._displa...
Try MongoDB configuration
def try_mongodb_opts(self, host="localhost", database_name='INGInious'): """ Try MongoDB configuration """ try: mongo_client = MongoClient(host=host) except Exception as e: self._display_warning("Cannot connect to MongoDB on host %s: %s" % (host, str(e))) retu...
Configure MongoDB
def configure_mongodb(self): """ Configure MongoDB """ self._display_info("Trying default configuration") host = "localhost" database_name = "INGInious" should_ask = True if self.try_mongodb_opts(host, database_name): should_ask = self._ask_boolean( ...
Configure task directory
def configure_task_directory(self): """ Configure task directory """ self._display_question( "Please choose a directory in which to store the course/task files. By default, the tool will put them in the current " "directory") task_directory = None while task_direc...
Download the chosen containers on all the agents
def download_containers(self, to_download, current_options): """ Download the chosen containers on all the agents """ if current_options["backend"] == "local": self._display_info("Connecting to the local Docker daemon...") try: docker_connection = docker.from_env(...
Configures the container dict
def configure_containers(self, current_options): """ Configures the container dict """ containers = [ ("default", "Default container. For Bash and Python 2 tasks"), ("cpp", "Contains gcc and g++ for compiling C++"), ("java7", "Contains Java 7"), ("java8sca...
Configure backup directory
def configure_backup_directory(self): """ Configure backup directory """ self._display_question("Please choose a directory in which to store the backup files. By default, the tool will them in the current " "directory") backup_directory = None while backup_...
Configures the LDAP plugin
def ldap_plugin(self): """ Configures the LDAP plugin """ name = self._ask_with_default("Authentication method name (will be displayed on the login page)", "LDAP") prefix = self._ask_with_default("Prefix to append to the username before db storage. Usefull when you have more than one auth method...
Configure the authentication
def configure_authentication(self, database): """ Configure the authentication """ options = {"plugins": [], "superadmins": []} self._display_info("We will now create the first user.") username = self._ask_with_default("Enter the login of the superadmin", "superadmin") realname...
Ensures that the app is properly closed
def _close_app(app, mongo_client, client): """ Ensures that the app is properly closed """ app.stop() client.close() mongo_client.close()
:param config: the configuration dict :return: A new app
def get_app(config): """ :param config: the configuration dict :return: A new app """ # First, disable debug. It will be enabled in the configuration, later. web.config.debug = False config = _put_configuration_defaults(config) mongo_client = MongoClient(host=config.get('mongo_opt', {}...
Must be called when the agent is starting
async def _init_clean(self): """ Must be called when the agent is starting """ # Data about running containers self._containers_running = {} self._container_for_job = {} self._student_containers_running = {} self._student_containers_for_job = {} self._containers...
Must be called when the agent is closing
async def _end_clean(self): """ Must be called when the agent is closing """ await self._timeout_watcher.clean() async def close_and_delete(container_id): try: await self._docker.remove_container(container_id) except: pass for con...
Get raw docker events and convert them to more readable objects, and then give them to self._docker_events_subscriber
async def _watch_docker_events(self): """ Get raw docker events and convert them to more readable objects, and then give them to self._docker_events_subscriber """ try: source = AsyncIteratorWrapper(self._docker.sync.event_stream(filters={"event": ["die", "oom"]})) async for i in...
Synchronous part of _new_job. Creates needed directories, copy files, and starts the container.
def __new_job_sync(self, message, future_results): """ Synchronous part of _new_job. Creates needed directories, copy files, and starts the container. """ course_id = message.course_id task_id = message.task_id debug = message.debug environment_name = message.environment ...
Handles a new job: starts the grading container
async def new_job(self, message: BackendNewJob): """ Handles a new job: starts the grading container """ self._logger.info("Received request for jobid %s", message.job_id) future_results = asyncio.Future() out = await self._loop.run_in_executor(None, lambda: self.__new_jo...
Creates a new student container. :param write_stream: stream on which to write the return value of the container (with a correctly formatted msgpack message)
async def create_student_container(self, job_id, parent_container_id, sockets_path, student_path, systemfiles_path, course_common_student_path, socket_id, environment_name, memory_limit, time_limit, hard_time_limit, share_network, write_stre...
Send a message to the stdin of a container, with the right data :param write_stream: asyncio write stream to the stdin of the container :param message: dict to be msgpacked and sent
async def _write_to_container_stdin(self, write_stream, message): """ Send a message to the stdin of a container, with the right data :param write_stream: asyncio write stream to the stdin of the container :param message: dict to be msgpacked and sent """ msg = msgpack.du...
Talk with a container. Sends the initial input. Allows to start student containers
async def handle_running_container(self, job_id, container_id, inputdata, debug, ports, orig_env, orig_memory_limit, orig_time_limit, orig_hard_time_limit, sockets_path, student_path, systemfiles_path, course_common_student_path, future_resul...
Handle a closing student container. Do some cleaning, verify memory limits, timeouts, ... and returns data to the associated grading container
async def handle_student_job_closing(self, container_id, retval): """ Handle a closing student container. Do some cleaning, verify memory limits, timeouts, ... and returns data to the associated grading container """ try: self._logger.debug("Closing student %s", conta...
Handles `kill` messages. Kill things.
async def kill_job(self, message: BackendKillJob): """ Handles `kill` messages. Kill things. """ try: if message.job_id in self._container_for_job: self._containers_killed[self._container_for_job[message.job_id]] = "killed" await self._docker.kill_container(se...
Handle a closing student container. Do some cleaning, verify memory limits, timeouts, ... and returns data to the backend
async def handle_job_closing(self, container_id, retval): """ Handle a closing student container. Do some cleaning, verify memory limits, timeouts, ... and returns data to the backend """ try: self._logger.debug("Closing %s", container_id) try: mes...
Get the available student and tutor lists for aggregation edition
def get_user_lists(self, course, aggregationid=''): """ Get the available student and tutor lists for aggregation edition""" tutor_list = course.get_staff() # Determine student list and if they are grouped student_list = list(self.database.aggregations.aggregate([ {"$match":...
Update aggregation and returns a list of errored students
def update_aggregation(self, course, aggregationid, new_data): """ Update aggregation and returns a list of errored students""" student_list = self.user_manager.get_course_registered_users(course, False) # If aggregation is new if aggregationid == 'None': # Remove _id for c...
Edit a aggregation
def GET_AUTH(self, courseid, aggregationid=''): # pylint: disable=arguments-differ """ Edit a aggregation """ course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=True) if course.is_lti(): raise web.notfound() return self.display_page(course, aggregation...
Edit a aggregation
def POST_AUTH(self, courseid, aggregationid=''): # pylint: disable=arguments-differ """ Edit a aggregation """ course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=True) if course.is_lti(): raise web.notfound() msg='' error = False errore...
Parse course registration or course creation and display the course list page
def POST_AUTH(self): # pylint: disable=arguments-differ """ Parse course registration or course creation and display the course list page """ username = self.user_manager.session_username() user_info = self.database.users.find_one({"username": username}) user_input = web.input() ...
Display main course list page
def show_page(self, success): """ Display main course list page """ username = self.user_manager.session_username() user_info = self.database.users.find_one({"username": username}) all_courses = self.course_factory.get_all_courses() # Display open_courses = {courseid: ...
Init asyncio and ZMQ. Starts a daemon thread in which the asyncio loops run. :return: a ZMQ context and a Thread object (as a tuple)
def start_asyncio_and_zmq(debug_asyncio=False): """ Init asyncio and ZMQ. Starts a daemon thread in which the asyncio loops run. :return: a ZMQ context and a Thread object (as a tuple) """ loop = ZMQEventLoop() asyncio.set_event_loop(loop) if debug_asyncio: loop.set_debug(True) zmq_c...
Run asyncio (should be called in a thread) and close the loop and the zmq context when the thread ends :param loop: :param zmq_context: :return:
def _run_asyncio(loop, zmq_context): """ Run asyncio (should be called in a thread) and close the loop and the zmq context when the thread ends :param loop: :param zmq_context: :return: """ try: asyncio.set_event_loop(loop) loop.run_forever() except: pass fina...
Restarts an agent when it is cancelled
async def _restart_on_cancel(logger, agent): """ Restarts an agent when it is cancelled """ while True: try: await agent.run() except asyncio.CancelledError: logger.exception("Restarting agent") pass
Helper that can start a simple complete INGInious arch locally if needed, or a client to a remote backend. Intended to be used on command line, makes uses of exit() and the logger inginious.frontend. :param configuration: configuration dict :param tasks_fs: FileSystemProvider to the courses/tasks folder...
def create_arch(configuration, tasks_fs, context, course_factory): """ Helper that can start a simple complete INGInious arch locally if needed, or a client to a remote backend. Intended to be used on command line, makes uses of exit() and the logger inginious.frontend. :param configuration: configurati...
Checks if user is authenticated and calls GET_AUTH or performs logout. Otherwise, returns the login template.
def GET(self, *args, **kwargs): """ Checks if user is authenticated and calls GET_AUTH or performs logout. Otherwise, returns the login template. """ if self.user_manager.session_logged_in(): if not self.user_manager.session_username() and not self.__class__.__name__ ...
Checks if user is authenticated and calls POST_AUTH or performs login and calls GET_AUTH. Otherwise, returns the login template.
def POST(self, *args, **kwargs): """ Checks if user is authenticated and calls POST_AUTH or performs login and calls GET_AUTH. Otherwise, returns the login template. """ if self.user_manager.session_logged_in(): if not self.user_manager.session_username() and not self...
Translate a /-separated PATH to the local filename syntax. Components that mean special things to the local file system (e.g. drive or directory names) are ignored. (XXX They should probably be diagnosed.)
def translate_path(self, path): """Translate a /-separated PATH to the local filename syntax. Components that mean special things to the local file system (e.g. drive or directory names) are ignored. (XXX They should probably be diagnosed.) """ # abandon query paramete...
Normalize the path
def normpath(self, path): """ Normalize the path """ path2 = posixpath.normpath(urllib.parse.unquote(path)) if path.endswith("/"): path2 += "/" return path2
Helper for the GET methods of the two following classes
def _get_submissions(course_factory, submission_manager, user_manager, translations, courseid, taskid, with_input, submissionid=None): """ Helper for the GET methods of the two following classes """ try: course = course_factory.get_course(courseid) except: raise APINotFound("Cou...
List all the submissions that the connected user made. Returns list of the form :: [ { "id": "submission_id1", "submitted_on": "date", "status" : "done", #can be "done", "waiting", "error" ...
def API_GET(self, courseid, taskid, submissionid): # pylint: disable=arguments-differ """ List all the submissions that the connected user made. Returns list of the form :: [ { "id": "submission_id1", ...
Creates a new submissions. Takes as (POST) input the key of the subproblems, with the value assigned each time. Returns - an error 400 Bad Request if all the input is not (correctly) given, - an error 403 Forbidden if you are not allowed to create a new submission for this task ...
def API_POST(self, courseid, taskid): # pylint: disable=arguments-differ """ Creates a new submissions. Takes as (POST) input the key of the subproblems, with the value assigned each time. Returns - an error 400 Bad Request if all the input is not (correctly) given, ...
GET request
def GET_AUTH(self, courseid, taskid): # pylint: disable=arguments-differ """ GET request """ course, task = self.get_course_and_check_rights(courseid, taskid) return self.page(course, task)
Get all data and display the page
def page(self, course, task): """ Get all data and display the page """ user_list = self.user_manager.get_course_registered_users(course, False) users = OrderedDict(sorted(list(self.user_manager.get_users_info(user_list).items()), key=lambda k: k[1][0] if k[1] ...
Returns true if users can register for this course
def is_registration_possible(self, user_info): """ Returns true if users can register for this course """ return self.get_accessibility().is_open() and self._registration.is_open() and self.is_user_accepted_by_access_control(user_info)
Return the AccessibleTime object associated with the accessibility of this course
def get_accessibility(self, plugin_override=True): """ Return the AccessibleTime object associated with the accessibility of this course """ vals = self._hook_manager.call_hook('course_accessibility', course=self, default=self._accessible) return vals[0] if len(vals) and plugin_override else sel...
Returns True if the user is allowed by the ACL
def is_user_accepted_by_access_control(self, user_info): """ Returns True if the user is allowed by the ACL """ if self.get_access_control_method() is None: return True elif not user_info: return False elif self.get_access_control_method() == "username": ...