Python web.notfound() Examples

The following are 30 code examples of web.notfound(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module web , or try the search function .
Example #1
Source File: group_edit.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
def GET_AUTH(self, courseid, groupid=''):  # pylint: disable=arguments-differ
        """ Edit a group """
        course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=True)

        if course.is_lti():
            raise web.notfound()

        if "download" in web.input():
            web.header('Content-Type', 'text/x-yaml', unique=True)
            web.header('Content-Disposition', 'attachment; filename="groups.yaml"', unique=True)
            groups = [{"description": group["description"],
                           "students": group["students"],
                           "size": group["size"],
                            "audiences": [str(c) for c in group["audiences"]]} for group in
                          self.user_manager.get_course_groups(course)]

            return yaml.dump(groups)

        return self.display_page(course) 
Example #2
Source File: download.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
def GET_AUTH(self, courseid):  # pylint: disable=arguments-differ
        """ GET request """
        course, __ = self.get_course_and_check_rights(courseid)
        user_input = web.input(tasks=[], aggregations=[], users=[])
        error = ""

        # First, check for a particular submission
        if "submission" in user_input:
            submission = self.database.submissions.find_one({"_id": ObjectId(user_input.submission),
                                                             "courseid": course.get_id(),
                                                             "status": {"$in": ["done", "error"]}})
            if submission is None:
                raise web.notfound()

            self._logger.info("Downloading submission %s - %s - %s - %s", submission['_id'], submission['courseid'],
                              submission['taskid'], submission['username'])
            archive, error = self.submission_manager.get_submission_archive(course, [submission], [])
            if not error:
                web.header('Content-Type', 'application/x-gzip', unique=True)
                web.header('Content-Disposition', 'attachment; filename="submissions.tgz"', unique=True)
                return archive

        # Else, display the complete page
        return self.display_page(course, user_input, error) 
Example #3
Source File: utils.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_course_and_check_rights(self, courseid, taskid=None, allow_all_staff=True):
        """ Returns the course with id ``courseid`` and the task with id ``taskid``, and verify the rights of the user.
            Raise web.notfound() when there is no such course of if the users has not enough rights.

            :param courseid: the course on which to check rights
            :param taskid: If not None, returns also the task with id ``taskid``
            :param allow_all_staff: allow admins AND tutors to see the page. If false, all only admins.
            :returns (Course, Task)
        """

        try:
            course = self.course_factory.get_course(courseid)
            if allow_all_staff:
                if not self.user_manager.has_staff_rights_on_course(course):
                    raise web.notfound()
            else:
                if not self.user_manager.has_admin_rights_on_course(course):
                    raise web.notfound()

            if taskid is None:
                return course, None
            else:
                return course, course.get_task(taskid)
        except:
            raise web.notfound() 
Example #4
Source File: task_edit_file.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
def action_download(self, courseid, taskid, path):
        """ Download a file or a directory """

        wanted_path = self.verify_path(courseid, taskid, path)
        if wanted_path is None:
            raise web.notfound()

        task_fs = self.task_factory.get_task_fs(courseid, taskid)
        (method, mimetype_or_none, file_or_url) = task_fs.distribute(wanted_path)

        if method == "local":
            web.header('Content-Type', mimetype_or_none)
            return file_or_url
        elif method == "url":
            raise web.redirect(file_or_url)
        else:
            raise web.notfound() 
Example #5
Source File: social.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
def process_callback(self, auth_id):
        auth_method = self.user_manager.get_auth_method(auth_id)
        if not auth_method:
            raise web.notfound()

        auth_storage = self.user_manager.session_auth_storage().setdefault(auth_id, {})
        user = auth_method.callback(auth_storage)
        if user and auth_storage.get("method", "") == "signin":
            if not self.user_manager.bind_user(auth_id, user):
                raise web.seeother("/signin?binderror")
        elif user and auth_storage.get("method", "") == "share":
            submission = self.submission_manager.get_submission(auth_storage["submissionid"], True)
            if submission:
                course = self.course_factory.get_course(submission["courseid"])
                task = course.get_task(submission["taskid"])
                auth_method.share(auth_storage, course, task, submission, self.user_manager.session_language())
            else:
                raise web.notfound()
        else:
            raise web.seeother("/signin?callbackerror")

        raise web.seeother(auth_storage.get("redir_url", "/")) 
Example #6
Source File: submissions.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
def POST_AUTH(self, courseid):  # pylint: disable=arguments-differ
        """ POST request """
        course, __ = self.get_course_and_check_rights(courseid)
        msgs = []

        if "replay" in web.input():
            if not self.user_manager.has_admin_rights_on_course(course):
                raise web.notfound()

            input = self.get_input()
            tasks = course.get_tasks()
            data, __ = self.get_submissions(course, input)
            for submission in data:
                self.submission_manager.replay_job(tasks[submission["taskid"]], submission)
            msgs.append(_("{0} selected submissions were set for replay.").format(str(len(data))))

        return self.page(course, msgs) 
Example #7
Source File: lti.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
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:
            course = self.course_factory.get_course(data["task"][0])
            if data["consumer_key"] not in course.lti_keys().keys():
                raise Exception()
        except:
            return self.template_helper.get_renderer().lti_bind(False, "", None, "Invalid LTI data")

        user_profile = self.database.users.find_one({"ltibindings." + data["task"][0] + "." + data["consumer_key"]: data["username"]})
        if user_profile:
            self.user_manager.connect_user(user_profile["username"], user_profile["realname"], user_profile["email"], user_profile["language"])

        if self.user_manager.session_logged_in():
            raise web.seeother(self.app.get_homepath() + "/lti/task")

        return self.template_helper.get_renderer().lti_login(False) 
Example #8
Source File: register.py    From INGInious with GNU Affero General Public License v3.0 6 votes vote down vote up
def POST(self):
        """ Handles POST request """
        if self.user_manager.session_logged_in() or not self.app.allow_registration:
            raise web.notfound()

        reset = None
        msg = ""
        error = False
        data = web.input()
        if "register" in data:
            msg, error = self.register_user(data)
        elif "lostpasswd" in data:
            msg, error = self.lost_passwd(data)
        elif "resetpasswd" in data:
            msg, error, reset = self.get_reset_data(data)
            if reset:
                msg, error = self.reset_passwd(data)
            if not error:
                reset = None

        return self.template_helper.get_renderer().register(reset, msg, error) 
Example #9
Source File: course.py    From INGInious with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_course(self, courseid):
        """ Return the course """
        try:
            course = self.course_factory.get_course(courseid)
        except:
            raise web.notfound()

        return course 
Example #10
Source File: submission.py    From INGInious with GNU Affero General Public License v3.0 5 votes vote down vote up
def fetch_submission(self, submissionid):
        try:
            submission = self.submission_manager.get_submission(submissionid, False)
            if not submission:
                raise web.notfound()
        except InvalidId as ex:
            self._logger.info("Invalid ObjectId : %s", submissionid)
            raise web.notfound()

        courseid = submission["courseid"]
        taskid = submission["taskid"]
        course, task = self.get_course_and_check_rights(courseid, taskid)
        return course, task, submission 
Example #11
Source File: submissions.py    From INGInious with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_input(self):
        """ Loads web input, initialise default values and check/sanitise some inputs from users """
        user_input = web.input(
            users=[],
            tasks=[],
            audiences=[],
            org_tags=[],
            grade_min='',
            grade_max='',
            sort_by="submitted_on",
            order='0',  # "0" for pymongo.DESCENDING, anything else for pymongo.ASCENDING
            limit='',
            filter_tags=[],
            filter_tags_presence=[],
            date_after='',
            date_before='',
            stat='with_stat',
        )

        # Sanitise inputs
        for item in itertools.chain(user_input.tasks, user_input.audiences):
            if not id_checker(item):
                raise web.notfound()

        if user_input.sort_by not in self._allowed_sort:
            raise web.notfound()

        digits = [user_input.grade_min, user_input.grade_max, user_input.order, user_input.limit]
        for d in digits:
            if d != '' and not d.isdigit():
                raise web.notfound()

        return user_input 
Example #12
Source File: replay.py    From INGInious with GNU Affero General Public License v3.0 5 votes vote down vote up
def POST_AUTH(self, courseid):  # pylint: disable=arguments-differ
        """ GET request """
        course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=False)
        user_input = web.input(tasks=[], audiences=[], users=[])

        if "submission" in user_input:
            # Replay a unique submission
            submission = self.database.submissions.find_one({"_id": ObjectId(user_input.submission)})
            if submission is None:
                raise web.notfound()

            web.header('Content-Type', 'application/json')
            self.submission_manager.replay_job(course.get_task(submission["taskid"]), submission)
            return json.dumps({"status": "waiting"})
        else:
            # Replay several submissions, check input
            tasks = course.get_tasks()
            error = False
            msg = _("Selected submissions were set for replay.")
            for i in user_input.tasks:
                if i not in tasks.keys():
                    msg = _("Task with id {} does not exist !").format(i)
                    error = True

            if not error:
                # Load submissions
                submissions = self.get_selected_submissions(course,
                                                            only_tasks=user_input.tasks or None,
                                                            only_users=user_input.users or None,
                                                            only_audiences=user_input.audiences or None,
                                                            keep_only_evaluation_submissions=user_input.type == "single")
                for submission in submissions:
                    self.submission_manager.replay_job(tasks[submission["taskid"]], submission)

            return self.show_page(course, web.input(), msg, error) 
Example #13
Source File: main.py    From BaoTa-Panel with GNU General Public License v3.0 5 votes vote down vote up
def notfound():
    errorStr = '''
    <meta charset="utf-8">
    <title>%s</title>
    </head><body>
    <h1>%s</h1>
        <p>%s</p>
    <hr>
    <address>%s 5.x <a href="https://www.bt.cn/bbs" target="_blank">%s</a></address>
    </body></html>
    ''' % (public.getMsg('PAGE_ERR_404_TITLE'),public.getMsg('PAGE_ERR_404_H1'),public.getMsg('PAGE_ERR_404_P1'),public.getMsg('NAME'),public.getMsg('PAGE_ERR_HELP'))
    return web.notfound(errorStr);
  
#定义500错误 
Example #14
Source File: __init__.py    From INGInious with GNU Affero General Public License v3.0 5 votes vote down vote up
def POST_AUTH(self):
        raise web.notfound() 
Example #15
Source File: __init__.py    From INGInious with GNU Affero General Public License v3.0 5 votes vote down vote up
def GET_AUTH(self, courseid):  # pylint: disable=arguments-differ
        """ GET request """
        course = self.course_factory.get_course(courseid)
        scoreboards = course.get_descriptor().get('scoreboard', [])

        try:
            names = {i: val["name"] for i, val in enumerate(scoreboards)}
        except:
            raise web.notfound("Invalid configuration")

        if len(names) == 0:
            raise web.notfound()

        return self.template_helper.get_custom_renderer('frontend/plugins/scoreboard').main(course, names) 
Example #16
Source File: server.py    From Apple-iOS-MDM-Server with MIT License 5 votes vote down vote up
def GET(self):
        # Enroll an iPad/iPhone/iPod when requested
        if 'Enroll.mobileconfig' in os.listdir('.'):
            web.header('Content-Type', 'application/x-apple-aspen-config;charset=utf-8')
            web.header('Content-Disposition', 'attachment;filename="Enroll.mobileconfig"')
            return open('Enroll.mobileconfig', "rb").read()
        else:
            raise web.notfound() 
Example #17
Source File: server.py    From Apple-iOS-MDM-Server with MIT License 5 votes vote down vote up
def GET(self):

        if 'CA.crt' in os.listdir('.'):
            web.header('Content-Type', 'application/octet-stream;charset=utf-8')
            web.header('Content-Disposition', 'attachment;filename="CA.crt"')
            return open('CA.crt', "rb").read()
        else:
            raise web.notfound() 
Example #18
Source File: server.py    From Apple-iOS-MDM-Server with MIT License 5 votes vote down vote up
def GET(self):

        if 'Manifest.plist' in os.listdir('.'):
            web.header('Content-Type', 'text/xml;charset=utf-8')
            return open('Manifest.plist', "rb").read()
        else:
            raise web.notfound() 
Example #19
Source File: auth.py    From netflix-proxy with MIT License 5 votes vote down vote up
def notfound():
  web.ctx.status = '404 Not Found'
  return web.notfound(str(render.__404()))


# Set a custom internal error message 
Example #20
Source File: main.py    From opennumber with GNU General Public License v3.0 5 votes vote down vote up
def handler_notfound():
    return web.notfound("page not found") 
Example #21
Source File: images.py    From jingwei with MIT License 5 votes vote down vote up
def GET(self,name):
        ext = name.split(".")[-1] # Gather extension
        if name.find('.')<0:
            ext = 'jpg'
        imfile = self.get_local( os.path.splitext(name)[0] )
        #print imfile
        try:
            web.header("Content-Type", cType[ext]) # Set the Header
            return open(imfile,"rb").read() # Notice 'rb' for reading images
        except:
            raise web.notfound() 
Example #22
Source File: lti.py    From INGInious with GNU Affero General Public License v3.0 5 votes vote down vote up
def GET_AUTH(self):
        data = self.user_manager.session_lti_info()
        if data is None:
            raise web.notfound()
        (courseid, taskid) = data['task']

        return BaseTaskPage(self).GET(courseid, taskid, True) 
Example #23
Source File: restful_webapi.py    From Some-Examples-of-Simple-Python-Script with GNU Affero General Public License v3.0 5 votes vote down vote up
def GET(self, id=None):
        global db, nextid

        if(len(id) == 0):
            return json.dumps(db)
        elif(int(id) in db):
            return json.dumps(db[int(id)])
        else:
            return web.notfound() 
Example #24
Source File: restful_webapi.py    From Some-Examples-of-Simple-Python-Script with GNU Affero General Public License v3.0 5 votes vote down vote up
def DELETE(self, id):
        global db, nextid

        if(int(id) in db):
            db.pop(int(id))
            return json.dumps({'deleted': int(id)})
        else:
            return web.notfound() 
Example #25
Source File: restful_webapi.py    From Some-Examples-of-Simple-Python-Script with GNU Affero General Public License v3.0 5 votes vote down vote up
def PUT(self, id):
        global db, nextid

        if(int(id) in db):
            db[int(id)] = json.loads(web.data())
            return json.dumps({'updated': int(id)})
        else:
            return web.notfound() 
Example #26
Source File: course_register.py    From INGInious with GNU Affero General Public License v3.0 5 votes vote down vote up
def basic_checks(self, courseid):
        try:
            course = self.course_factory.get_course(courseid)
        except:
            raise web.notfound()

        username = self.user_manager.session_username()
        user_info = self.user_manager.get_user_info(username)

        if self.user_manager.course_is_user_registered(course, username) or not course.is_registration_possible(user_info):
            raise web.seeother(self.app.get_homepath() + "/course/" + course.get_id())

        return course, username 
Example #27
Source File: social.py    From INGInious with GNU Affero General Public License v3.0 5 votes vote down vote up
def process_signin(self,auth_id):
        auth_method = self.user_manager.get_auth_method(auth_id)
        if not auth_method:
            raise web.notfound()

        auth_storage = self.user_manager.session_auth_storage().setdefault(auth_id, {})
        auth_storage["redir_url"] = web.ctx.env.get('HTTP_REFERER', '/')
        auth_storage["method"] = "signin"
        auth_link = auth_method.get_auth_link(auth_storage)
        raise web.seeother(auth_link) 
Example #28
Source File: social.py    From INGInious with GNU Affero General Public License v3.0 5 votes vote down vote up
def process_share(self, auth_id):
        auth_method = self.user_manager.get_auth_method(auth_id)
        if not auth_method:
            raise web.notfound()

        auth_storage = self.user_manager.session_auth_storage().setdefault(auth_id, {})
        auth_storage["redir_url"] = web.ctx.env.get('HTTP_REFERER', '/')
        auth_storage["method"] = "share"
        auth_storage["submissionid"] = web.input().get("submissionid", "")
        auth_link = auth_method.get_auth_link(auth_storage, True)
        raise web.seeother(auth_link) 
Example #29
Source File: utils.py    From INGInious with GNU Affero General Public License v3.0 5 votes vote down vote up
def show_page(self, page):
        static_directory = self.app.static_directory
        language = self.user_manager.session_language()

        # Check for the file
        filename = None
        mtime = None
        filepaths = [os.path.join(static_directory, page + ".yaml"),
                     os.path.join(static_directory, page + "." + language + ".yaml")]

        for filepath in filepaths:
            if os.path.exists(filepath):
                filename = filepath
                mtime = os.stat(filepath).st_mtime

        if not filename:
            raise web.notfound()

        # Check and update cache
        if INGIniousStaticPage.cache.get(filename, (0, None))[0] < mtime:
            with open(filename, "r") as f:
                INGIniousStaticPage.cache[filename] = mtime, custom_yaml.load(f)

        filecontent = INGIniousStaticPage.cache[filename][1]
        title = filecontent["title"]
        content = ParsableText.rst(filecontent["content"], initial_header_level=2)

        return self.template_helper.get_renderer().static(title, content) 
Example #30
Source File: tasks.py    From INGInious with GNU Affero General Public License v3.0 5 votes vote down vote up
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 handle_course_unavailable(self.app.get_homepath(), self.template_helper, self.user_manager, course)

            path_norm = posixpath.normpath(urllib.parse.unquote(path))

            if taskid == "$common":
                public_folder = course.get_fs().from_subfolder("$common").from_subfolder("public")
            else:

                task = course.get_task(taskid)
                if not self.user_manager.task_is_visible_by_user(task):  # ignore LTI check here
                    return self.template_helper.get_renderer().task_unavailable()

                public_folder = task.get_fs().from_subfolder("public")
            (method, mimetype_or_none, file_or_url) = public_folder.distribute(path_norm, False)

            if method == "local":
                web.header('Content-Type', mimetype_or_none)
                return file_or_url
            elif method == "url":
                raise web.redirect(file_or_url)
            else:
                raise web.notfound()
        except web.HTTPError as error_or_redirect:
            raise error_or_redirect
        except:
            if web.config.debug:
                raise
            else:
                raise web.notfound()