How to use the cherrypy.HTTPError function in CherryPy

To help you get started, we’ve selected a few CherryPy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github dmwm / WMCore / src / python / WMCore / REST / Error.py View on Github external
offset = err.errobj.args[0].offset
            sql = sql[:offset] + "<**>" + sql[offset:]
        cherrypy.log("SERVER DATABASE ERROR %d/%d %s %s.%s %s [instance: %s] (%s);"
                     " last statement: %s; binds: %s, %s; offset: %s"
                     % (err.http_code, err.app_code, err.message,
                        getattr(err.errobj, "__module__", "__builtins__"),
                        err.errobj.__class__.__name__,
                        err.errid, err.instance, str(err.errobj).rstrip(),
                        sql, binds, kwbinds, offset))
        for line in err.trace.rstrip().split("\n"): cherrypy.log("  " + line)
        cherrypy.response.headers["X-REST-Status"] = str(err.app_code)
        cherrypy.response.headers["X-Error-HTTP"] = str(err.http_code)
        cherrypy.response.headers["X-Error-ID"] = err.errid
        report_error_header("X-Error-Detail", err.message)
        report_error_header("X-Error-Info", err.info)
        if throw: raise cherrypy.HTTPError(err.http_code, err.message)
    elif isinstance(err, RESTError):
        if err.errobj:
            cherrypy.log("SERVER REST ERROR %s.%s %s (%s); derived from %s.%s (%s)"
                         % (err.__module__, err.__class__.__name__,
                            err.errid, err.message,
                            getattr(err.errobj, "__module__", "__builtins__"),
                            err.errobj.__class__.__name__,
                            str(err.errobj).rstrip()))
            trace = err.trace
        else:
            cherrypy.log("SERVER REST ERROR %s.%s %s (%s)"
                         % (err.__module__, err.__class__.__name__,
                            err.errid, err.message))
        for line in trace.rstrip().split("\n"): cherrypy.log("  " + line)
        cherrypy.response.headers["X-REST-Status"] = str(err.app_code)
        cherrypy.response.headers["X-Error-HTTP"] = str(err.http_code)
github sandialabs / slycat / packages / slycat / web / server / worker / chunker / table.py View on Github external
def get_table_chunker_metadata(self, arguments):
    """Called to retrieve metadata describing the underlying table."""
    response = self.get_metadata()
    if isinstance(response, cherrypy.HTTPError):
      raise response
    return response
github bsmedberg / mozilla-weekly-updates / weeklyupdates / main.py View on Github external
def login(self, **kwargs):
        if cherrypy.request.method.upper() == 'POST':
            cur = model.get_cursor()

            returnTo = kwargs.get('returnTo', cherrypy.url('/'))

            assertion = kwargs.pop('loginAssertion')
            if assertion == '':
                logged_out()
                raise cherrypy.HTTPRedirect(returnTo)

            try:
                result = browserid.verify(assertion, cherrypy.request.base)
            except browserid.ConnectionError:
                raise cherrypy.HTTPError(503, "Login connection error")
            except browserid.TrustError:
                raise cherrypy.HTTPError(409, "Invalid login")

            loginid = result['email']

            cur.execute('''SELECT userid FROM users
                           WHERE userid = ?''',
                        (loginid,))
            if cur.fetchone() is None:
                cur.execute('''INSERT INTO users
                               (userid) VALUES (?)''',
                            (loginid,))
                logged_in(loginid)
                raise cherrypy.HTTPRedirect(cherrypy.url('/preferences'))
            logged_in(loginid)
            raise cherrypy.HTTPRedirect(returnTo)
github clips / pattern / pattern / server / cherrypy / cherrypy / lib / jsontools.py View on Github external
other reason the request entity cannot be deserialized from JSON,
    it will raise "400 Bad Request: Invalid JSON document".

    You must be using Python 2.6 or greater, or have the 'simplejson'
    package importable; otherwise, ValueError is raised during processing.
    """
    request = cherrypy.serving.request
    if isinstance(content_type, basestring):
        content_type = [content_type]

    if force:
        if debug:
            cherrypy.log('Removing body processors %s' %
                         repr(request.body.processors.keys()), 'TOOLS.JSON_IN')
        request.body.processors.clear()
        request.body.default_proc = cherrypy.HTTPError(
            415, 'Expected an entity of content type %s' %
            ', '.join(content_type))

    for ct in content_type:
        if debug:
            cherrypy.log('Adding body processor for %s' % ct, 'TOOLS.JSON_IN')
        request.body.processors[ct] = processor
github dmwm / WMCore / src / python / WMCore / HTTPFrontEnd / RequestManager / ReqMgrWebTools.py View on Github external
if toks == ['']:
            return []
        result = [int(tok) for tok in toks]
    elif isinstance(l, int):
        result = [l]
    else:
        raise cherrypy.HTTPError(400, "Bad Run list of type " + type(l).__name__)

    # If we're here, we have a list of runs
    for r in result:
        try:
            tmp = int(r)
        except ValueError:
            raise cherrypy.HTTPError(400, "Given runList without integer run numbers")
        if not tmp == r:
            raise cherrypy.HTTPError(400, "Given runList without valid integer run numbers")
    return result
    #raise RuntimeError, "Bad Run list of type " + type(l).__name__
github whisperaven / 0ops.exed / exe / api / handler.py View on Github external
""" Handle api request by invoke ``runner.handle()``.

        All exception raised by runner will be catched here, and convert them
        into cherrypy `HTTPError()` with corresponding status code and message.
        """
        try:
            return self._runner.handle(*args, **kwargs)
        except JobDeleteError:
            raise cherrypy.HTTPError(status.BAD_REQUEST, excinst().message)
        except JobConflictError:
            raise cherrypy.HTTPError(status.CONFLICT, excinst().message)
        except JobNotSupportedError:
            raise cherrypy.HTTPError(status.INTERNAL_SERVER_ERROR,
                                     excinst().message)
        except (JobNotExistsError, ExecutorNoMatchError):
            raise cherrypy.HTTPError(status.NOT_FOUND, excinst().message)
        except:
            cherrypy.log("error response 500", traceback=True)
            raise cherrypy.HTTPError(status.INTERNAL_SERVER_ERROR)
github ceph / ceph / src / pybind / mgr / dashboard / controllers / cephfs.py View on Github external
def _cephfs_instance(fs_id):
        """
        :param fs_id: The filesystem identifier.
        :type fs_id: int | str
        :return: A instance of the CephFS class.
        """
        fs_name = CephFS_.fs_name_from_id(fs_id)
        if fs_name is None:
            raise cherrypy.HTTPError(404, "CephFS id {} not found".format(fs_id))
        return CephFS_(fs_name)
github cherrypy / cherrypy / py3 / cherrypy / lib / cptools.py View on Github external
if self.debug:
                cherrypy.log('routing %r to login_screen' % path, 'TOOLS.SESSAUTH')
            return self.login_screen(**request.params)
        elif path.endswith('do_login'):
            if request.method != 'POST':
                response.headers['Allow'] = "POST"
                if self.debug:
                    cherrypy.log('do_login requires POST', 'TOOLS.SESSAUTH')
                raise cherrypy.HTTPError(405)
            if self.debug:
                cherrypy.log('routing %r to do_login' % path, 'TOOLS.SESSAUTH')
            return self.do_login(**request.params)
        elif path.endswith('do_logout'):
            if request.method != 'POST':
                response.headers['Allow'] = "POST"
                raise cherrypy.HTTPError(405)
            if self.debug:
                cherrypy.log('routing %r to do_logout' % path, 'TOOLS.SESSAUTH')
            return self.do_logout(**request.params)
        else:
            if self.debug:
                cherrypy.log('No special path, running do_check', 'TOOLS.SESSAUTH')
            return self.do_check()
github jfisteus / eyegrade / eyegrade / server / server.py View on Github external
def close(self):
        """Closes the current session.

        Session should have been opened first with /init.

        """
        if not 'exam_config' in cherrypy.session:
            raise cherrypy.HTTPError('403 Forbidden',
                                     'Session was not open')
        cherrypy.session.clear()
        cherrypy.lib.sessions.expire()
        return 'OK'
    close.exposed = True