Python cherrypy.HTTPError() Examples

The following are 30 code examples of cherrypy.HTTPError(). 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 cherrypy , or try the search function .
Example #1
Source File: webui.py    From disk_perf_test_tool with Apache License 2.0 6 votes vote down vote up
def sensors(self, start, stop, step, name):
        try:
            start = to_timestamp(start)
            stop = to_timestamp(stop)

            with self.storage.lock:
                data = self.storage.data[name]
        except Exception:
            logger.exception("During parse input data")
            raise cherrypy.HTTPError("Wrong date format")

        if step != 1000:
            raise cherrypy.HTTPError("Step must be equals to 1s")

        num = stop - start

        if len(data) > num:
            data = data[-num:]
        else:
            data = [0] * (num - len(data)) + data

        return data 
Example #2
Source File: _cpreqbody.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def decode_entity(self, value):
        """Return a given byte encoded value as a string"""
        for charset in self.attempt_charsets:
            try:
                value = value.decode(charset)
            except UnicodeDecodeError:
                pass
            else:
                self.charset = charset
                return value
        else:
            raise cherrypy.HTTPError(
                400,
                'The request entity could not be decoded. The following '
                'charsets were attempted: %s' % repr(self.attempt_charsets)
            ) 
Example #3
Source File: cptools.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run(self):
        request = cherrypy.serving.request
        response = cherrypy.serving.response

        path = request.path_info
        if path.endswith('login_screen'):
            self._debug_message('routing %(path)r to login_screen', locals())
            response.body = self.login_screen()
            return True
        elif path.endswith('do_login'):
            if request.method != 'POST':
                response.headers['Allow'] = 'POST'
                self._debug_message('do_login requires POST')
                raise cherrypy.HTTPError(405)
            self._debug_message('routing %(path)r to do_login', locals())
            return self.do_login(**request.params)
        elif path.endswith('do_logout'):
            if request.method != 'POST':
                response.headers['Allow'] = 'POST'
                raise cherrypy.HTTPError(405)
            self._debug_message('routing %(path)r to do_logout', locals())
            return self.do_logout(**request.params)
        else:
            self._debug_message('No special path, running do_check')
            return self.do_check() 
Example #4
Source File: _cpreqbody.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
def decode_entity(self , value):
        """Return a given byte encoded value as a string"""
        for charset in self.attempt_charsets:
            try:
                value = value.decode(charset)
            except UnicodeDecodeError:
                pass
            else:
                self.charset = charset
                return value
        else:
            raise cherrypy.HTTPError(
                400,
                'The request entity could not be decoded. The following '
                'charsets were attempted: %s' % repr(self.attempt_charsets)
            ) 
Example #5
Source File: cptools.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        request = cherrypy.serving.request
        response = cherrypy.serving.response

        path = request.path_info
        if path.endswith('login_screen'):
            self._debug_message('routing %(path)r to login_screen', locals())
            response.body = self.login_screen()
            return True
        elif path.endswith('do_login'):
            if request.method != 'POST':
                response.headers['Allow'] = 'POST'
                self._debug_message('do_login requires POST')
                raise cherrypy.HTTPError(405)
            self._debug_message('routing %(path)r to do_login', locals())
            return self.do_login(**request.params)
        elif path.endswith('do_logout'):
            if request.method != 'POST':
                response.headers['Allow'] = 'POST'
                raise cherrypy.HTTPError(405)
            self._debug_message('routing %(path)r to do_logout', locals())
            return self.do_logout(**request.params)
        else:
            self._debug_message('No special path, running do_check')
            return self.do_check() 
Example #6
Source File: _cperror.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def set_response(self):
        """Modify cherrypy.response status, headers, and body to represent
        self.

        CherryPy uses this internally, but you can also use it to create an
        HTTPError object and set its output without *raising* the exception.
        """
        response = cherrypy.serving.response

        clean_headers(self.code)

        # In all cases, finalize will be called after this method,
        # so don't bother cleaning up response values here.
        response.status = self.status
        tb = None
        if cherrypy.serving.request.show_tracebacks:
            tb = format_exc()

        response.headers.pop('Content-Length', None)

        content = self.get_error_page(self.status, traceback=tb,
                                      message=self._message)
        response.body = content

        _be_ie_unfriendly(self.code) 
Example #7
Source File: httputil.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def qvalue(self):
        'The qvalue, or priority, of this value.'
        val = self.params.get('q', '1')
        if isinstance(val, HeaderElement):
            val = val.value
        try:
            return float(val)
        except ValueError as val_err:
            """Fail client requests with invalid quality value.

            Ref: https://github.com/cherrypy/cherrypy/issues/1370
            """
            raise cherrypy.HTTPError(
                400,
                'Malformed HTTP header: `{}`'.
                format(str(self)),
            ) from val_err 
Example #8
Source File: _cprequest.py    From opsbro with MIT License 6 votes vote down vote up
def process_query_string(self):
        """Parse the query string into Python structures. (Core)"""
        try:
            p = httputil.parse_query_string(
                self.query_string, encoding=self.query_string_encoding)
        except UnicodeDecodeError:
            raise cherrypy.HTTPError(
                404, "The given query string could not be processed. Query "
                "strings for this resource must be encoded with %r." %
                self.query_string_encoding)

        # Python 2 only: keyword arguments must be byte strings (type 'str').
        if not py3k:
            for key, value in p.items():
                if isinstance(key, unicode):
                    del p[key]
                    p[key.encode(self.query_string_encoding)] = value
        self.params.update(p) 
Example #9
Source File: test_etags.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setup_server():
        class Root:

            @cherrypy.expose
            def resource(self):
                return 'Oh wah ta goo Siam.'

            @cherrypy.expose
            def fail(self, code):
                code = int(code)
                if 300 <= code <= 399:
                    raise cherrypy.HTTPRedirect([], code)
                else:
                    raise cherrypy.HTTPError(code)

            @cherrypy.expose
            # In Python 3, tools.encode is on by default
            @cherrypy.config(**{'tools.encode.on': True})
            def unicoded(self):
                return ntou('I am a \u1ee4nicode string.', 'escape')

        conf = {'/': {'tools.etags.on': True,
                      'tools.etags.autotags': True,
                      }}
        cherrypy.tree.mount(Root(), config=conf) 
Example #10
Source File: api_logics.py    From smarthome with GNU General Public License v3.0 6 votes vote down vote up
def get_body(self, text=False):
        """
        Get content body of received request header

        :return:
        """
        cl = cherrypy.request.headers.get('Content-Length', 0)
        if cl == 0:
            # cherrypy.reponse.headers["Status"] = "400"
            # return 'Bad request'
            raise cherrypy.HTTPError(status=411)
        rawbody = cherrypy.request.body.read(int(cl))
        self.logger.debug("ServicesController(): get_body(): rawbody = {}".format(rawbody))
        try:
            if text:
                params = rawbody.decode('utf-8')
            else:
                params = json.loads(rawbody.decode('utf-8'))
        except Exception as e:
            self.logger.warning("ServicesController(): get_body(): Exception {}".format(e))
            return None
        return params 
Example #11
Source File: api_plugin.py    From smarthome with GNU General Public License v3.0 6 votes vote down vote up
def get_body(self):
        """
        Get content body of received request header

        :return:
        """
        cl = cherrypy.request.headers.get('Content-Length', 0)
        if cl == 0:
            # cherrypy.reponse.headers["Status"] = "400"
            # return 'Bad request'
            raise cherrypy.HTTPError(status=411)
        rawbody = cherrypy.request.body.read(int(cl))
        self.logger.debug("PluginController(): ___(): rawbody = {}".format(rawbody))
        try:
            params = json.loads(rawbody.decode('utf-8'))
        except Exception as e:
            self.logger.warning("PluginController(): ___(): Exception {}".format(e))
            return None
        return params 
Example #12
Source File: auth.py    From opsbro with MIT License 6 votes vote down vote up
def digest_auth(realm, users, debug=False):
    """If auth fails, raise 401 with a digest authentication header.

    realm
        A string containing the authentication realm.
    users
        A dict of the form: {username: password} or a callable returning
        a dict.
    """
    if check_auth(users, realm=realm):
        if debug:
            cherrypy.log('Auth successful', 'TOOLS.DIGEST_AUTH')
        return

    # inform the user-agent this path is protected
    cherrypy.serving.response.headers[
        'www-authenticate'] = httpauth.digestAuth(realm)

    raise cherrypy.HTTPError(
        401, "You are not authorized to access that resource") 
Example #13
Source File: api_files.py    From smarthome with GNU General Public License v3.0 6 votes vote down vote up
def save_scenes_config(self, filename):
        """
        Save scene configuration

        :return: status dict
        """
        params = None
        params = self.get_body(text=True)
        if params is None:
            self.logger.warning("FilesController.save_scenes_config(): Bad, request")
            raise cherrypy.HTTPError(status=411)
        self.logger.debug("FilesController.save_scenes_config(): '{}'".format(params))


        filename = os.path.join(self.scenes_dir, filename + '.yaml')
        read_data = None
        with open(filename, 'w') as f:
            f.write(params)

        result = {"result": "ok"}
        return json.dumps(result) 
Example #14
Source File: _cprequest.py    From opsbro with MIT License 6 votes vote down vote up
def run(self, point):
        """Execute all registered Hooks (callbacks) for the given point."""
        exc = None
        hooks = self[point]
        hooks.sort()
        for hook in hooks:
            # Some hooks are guaranteed to run even if others at
            # the same hookpoint fail. We will still log the failure,
            # but proceed on to the next hook. The only way
            # to stop all processing from one of these hooks is
            # to raise SystemExit and stop the whole server.
            if exc is None or hook.failsafe:
                try:
                    hook()
                except (KeyboardInterrupt, SystemExit):
                    raise
                except (cherrypy.HTTPError, cherrypy.HTTPRedirect,
                        cherrypy.InternalRedirect):
                    exc = sys.exc_info()[1]
                except:
                    exc = sys.exc_info()[1]
                    cherrypy.log(traceback=True, severity=40)
        if exc:
            raise exc 
Example #15
Source File: api_services.py    From smarthome with GNU General Public License v3.0 6 votes vote down vote up
def get_body(self, text=False):
        """
        Get content body of received request header

        :return:
        """
        cl = cherrypy.request.headers.get('Content-Length', 0)
        if cl == 0:
            # cherrypy.reponse.headers["Status"] = "400"
            # return 'Bad request'
            raise cherrypy.HTTPError(status=411)
        rawbody = cherrypy.request.body.read(int(cl))
        self.logger.debug("ServicesController(): get_body(): rawbody = {}".format(rawbody))
        try:
            if text:
                params = rawbody.decode('utf-8')
            else:
                params = json.loads(rawbody.decode('utf-8'))
        except Exception as e:
            self.logger.warning("ServicesController(): get_body(): Exception {}".format(e))
            return None
        return params 
Example #16
Source File: api_services.py    From smarthome with GNU General Public License v3.0 6 votes vote down vote up
def yamlcheck(self):
        """
        Check syntax of YAML configuration

        :return: status dict
        """
        params = self.get_body(text=True)
        if params is None:
            self.logger.warning("ServicesController(): yamlcheck(): Bad, request")
            raise cherrypy.HTTPError(status=411)
        self.logger.info("ServicesController(): yamlcheck(): '{}'".format(params))

        return self.yaml_syntax_checker(params)


    # ======================================================================
    #  /api/server/yamlconvert
    # 
Example #17
Source File: api_services.py    From smarthome with GNU General Public License v3.0 6 votes vote down vote up
def evalcheck(self):
        """
        Check syntax of eval expression

        :return: status dict
        """
        params = self.get_body(text=False)
        if params is None:
            self.logger.warning("ServicesController(): evalcheck(): Bad, request")
            raise cherrypy.HTTPError(status=411)
        self.logger.info("ServicesController(): evalcheck(): {}".format(params))

        expanded_code, eval_result = self.eval_syntax_checker(params['expression'], params['relative_to'])
        result_type = str(type(eval_result))
        if result_type.startswith("<class '"):
            result_type = result_type[len("<class '"):]
            result_type = result_type[:-2]
        result = {'expression': expanded_code, 'result': eval_result, 'type': result_type}
        # return json.dumps({'expression': 'Expandierter Ausdruck (Antwort vom Server)', 'result': '42 (Antwort vom Server)'})
        return json.dumps(result)


    # ======================================================================
    #  /api/server/yamlcheck
    # 
Example #18
Source File: _cperror.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def set_response(self):
        """Modify cherrypy.response status, headers, and body to represent
        self.

        CherryPy uses this internally, but you can also use it to create an
        HTTPError object and set its output without *raising* the exception.
        """
        import cherrypy

        response = cherrypy.serving.response

        clean_headers(self.code)

        # In all cases, finalize will be called after this method,
        # so don't bother cleaning up response values here.
        response.status = self.status
        tb = None
        if cherrypy.serving.request.show_tracebacks:
            tb = format_exc()

        response.headers.pop('Content-Length', None)

        content = self.get_error_page(self.status, traceback=tb,
                                      message=self._message)
        response.body = content

        _be_ie_unfriendly(self.code) 
Example #19
Source File: cptools.py    From opsbro with MIT License 5 votes vote down vote up
def referer(pattern, accept=True, accept_missing=False, error=403,
            message='Forbidden Referer header.', debug=False):
    """Raise HTTPError if Referer header does/does not match the given pattern.

    pattern
        A regular expression pattern to test against the Referer.

    accept
        If True, the Referer must match the pattern; if False,
        the Referer must NOT match the pattern.

    accept_missing
        If True, permit requests with no Referer header.

    error
        The HTTP error code to return to the client on failure.

    message
        A string to include in the response body on failure.

    """
    try:
        ref = cherrypy.serving.request.headers['Referer']
        match = bool(re.match(pattern, ref))
        if debug:
            cherrypy.log('Referer %r matches %r' % (ref, pattern),
                         'TOOLS.REFERER')
        if accept == match:
            return
    except KeyError:
        if debug:
            cherrypy.log('No Referer header', 'TOOLS.REFERER')
        if accept_missing:
            return

    raise cherrypy.HTTPError(error, message) 
Example #20
Source File: cptools.py    From opsbro with MIT License 5 votes vote down vote up
def allow(methods=None, debug=False):
    """Raise 405 if request.method not in methods (default ['GET', 'HEAD']).

    The given methods are case-insensitive, and may be in any order.
    If only one method is allowed, you may supply a single string;
    if more than one, supply a list of strings.

    Regardless of whether the current method is allowed or not, this
    also emits an 'Allow' response header, containing the given methods.
    """
    if not isinstance(methods, (tuple, list)):
        methods = [methods]
    methods = [m.upper() for m in methods if m]
    if not methods:
        methods = ['GET', 'HEAD']
    elif 'GET' in methods and 'HEAD' not in methods:
        methods.append('HEAD')

    cherrypy.response.headers['Allow'] = ', '.join(methods)
    if cherrypy.request.method not in methods:
        if debug:
            cherrypy.log('request.method %r not in methods %r' %
                         (cherrypy.request.method, methods), 'TOOLS.ALLOW')
        raise cherrypy.HTTPError(405)
    else:
        if debug:
            cherrypy.log('request.method %r in methods %r' %
                         (cherrypy.request.method, methods), 'TOOLS.ALLOW') 
Example #21
Source File: cptools.py    From opsbro with MIT License 5 votes vote down vote up
def validate_since():
    """Validate the current Last-Modified against If-Modified-Since headers.

    If no code has set the Last-Modified response header, then no validation
    will be performed.
    """
    response = cherrypy.serving.response
    lastmod = response.headers.get('Last-Modified')
    if lastmod:
        status, reason, msg = _httputil.valid_status(response.status)

        request = cherrypy.serving.request

        since = request.headers.get('If-Unmodified-Since')
        if since and since != lastmod:
            if (status >= 200 and status <= 299) or status == 412:
                raise cherrypy.HTTPError(412)

        since = request.headers.get('If-Modified-Since')
        if since and since == lastmod:
            if (status >= 200 and status <= 299) or status == 304:
                if request.method in ("GET", "HEAD"):
                    raise cherrypy.HTTPRedirect([], 304)
                else:
                    raise cherrypy.HTTPError(412)


#                                Tool code                                # 
Example #22
Source File: _cpreqbody.py    From opsbro with MIT License 5 votes vote down vote up
def process(self):
        """Process the request entity based on its Content-Type."""
        # "The presence of a message-body in a request is signaled by the
        # inclusion of a Content-Length or Transfer-Encoding header field in
        # the request's message-headers."
        # It is possible to send a POST request with no body, for example;
        # however, app developers are responsible in that case to set
        # cherrypy.request.process_body to False so this method isn't called.
        h = cherrypy.serving.request.headers
        if 'Content-Length' not in h and 'Transfer-Encoding' not in h:
            raise cherrypy.HTTPError(411)

        self.fp = SizedReader(self.fp, self.length,
                              self.maxbytes, bufsize=self.bufsize,
                              has_trailers='Trailer' in h)
        super(RequestBody, self).process()

        # Body params should also be a part of the request_params
        # add them in here.
        request_params = self.request_params
        for key, value in self.params.items():
            # Python 2 only: keyword arguments must be byte strings (type
            # 'str').
            if sys.version_info < (3, 0):
                if isinstance(key, unicode):
                    key = key.encode('ISO-8859-1')

            if key in request_params:
                if not isinstance(request_params[key], list):
                    request_params[key] = [request_params[key]]
                request_params[key].append(value)
            else:
                request_params[key] = value 
Example #23
Source File: _cpdispatch.py    From opsbro with MIT License 5 votes vote down vote up
def __call__(self, path_info):
        """Set handler and config for the current request."""
        request = cherrypy.serving.request
        resource, vpath = self.find_handler(path_info)

        if resource:
            # Set Allow header
            avail = [m for m in dir(resource) if m.isupper()]
            if "GET" in avail and "HEAD" not in avail:
                avail.append("HEAD")
            avail.sort()
            cherrypy.serving.response.headers['Allow'] = ", ".join(avail)

            # Find the subhandler
            meth = request.method.upper()
            func = getattr(resource, meth, None)
            if func is None and meth == "HEAD":
                func = getattr(resource, "GET", None)
            if func:
                # Grab any _cp_config on the subhandler.
                if hasattr(func, "_cp_config"):
                    request.config.update(func._cp_config)

                # Decode any leftover %2F in the virtual_path atoms.
                vpath = [x.replace("%2F", "/") for x in vpath]
                request.handler = LateParamPageHandler(func, *vpath)
            else:
                request.handler = cherrypy.HTTPError(405)
        else:
            request.handler = cherrypy.NotFound() 
Example #24
Source File: _cpdispatch.py    From opsbro with MIT License 5 votes vote down vote up
def __call__(self):
        try:
            return self.callable(*self.args, **self.kwargs)
        except TypeError:
            x = sys.exc_info()[1]
            try:
                test_callable_spec(self.callable, self.args, self.kwargs)
            except cherrypy.HTTPError:
                raise sys.exc_info()[1]
            except:
                raise x
            raise 
Example #25
Source File: _cperror.py    From opsbro with MIT License 5 votes vote down vote up
def __init__(self, path=None):
        if path is None:
            import cherrypy
            request = cherrypy.serving.request
            path = request.script_name + request.path_info
        self.args = (path,)
        HTTPError.__init__(self, 404, "The path '%s' was not found." % path) 
Example #26
Source File: cptools.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def allow(methods=None, debug=False):
    """Raise 405 if request.method not in methods (default ['GET', 'HEAD']).

    The given methods are case-insensitive, and may be in any order.
    If only one method is allowed, you may supply a single string;
    if more than one, supply a list of strings.

    Regardless of whether the current method is allowed or not, this
    also emits an 'Allow' response header, containing the given methods.
    """
    if not isinstance(methods, (tuple, list)):
        methods = [methods]
    methods = [m.upper() for m in methods if m]
    if not methods:
        methods = ['GET', 'HEAD']
    elif 'GET' in methods and 'HEAD' not in methods:
        methods.append('HEAD')

    cherrypy.response.headers['Allow'] = ', '.join(methods)
    if cherrypy.request.method not in methods:
        if debug:
            cherrypy.log('request.method %r not in methods %r' %
                         (cherrypy.request.method, methods), 'TOOLS.ALLOW')
        raise cherrypy.HTTPError(405)
    else:
        if debug:
            cherrypy.log('request.method %r in methods %r' %
                         (cherrypy.request.method, methods), 'TOOLS.ALLOW') 
Example #27
Source File: _cperror.py    From opsbro with MIT License 5 votes vote down vote up
def set_response(self):
        """Modify cherrypy.response status, headers, and body to represent
        self.

        CherryPy uses this internally, but you can also use it to create an
        HTTPError object and set its output without *raising* the exception.
        """
        import cherrypy

        response = cherrypy.serving.response

        clean_headers(self.code)

        # In all cases, finalize will be called after this method,
        # so don't bother cleaning up response values here.
        response.status = self.status
        tb = None
        if cherrypy.serving.request.show_tracebacks:
            tb = format_exc()

        response.headers.pop('Content-Length', None)

        content = self.get_error_page(self.status, traceback=tb,
                                      message=self._message)
        response.body = content

        _be_ie_unfriendly(self.code) 
Example #28
Source File: cptools.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def referer(pattern, accept=True, accept_missing=False, error=403,
            message='Forbidden Referer header.', debug=False):
    """Raise HTTPError if Referer header does/does not match the given pattern.

    pattern
        A regular expression pattern to test against the Referer.

    accept
        If True, the Referer must match the pattern; if False,
        the Referer must NOT match the pattern.

    accept_missing
        If True, permit requests with no Referer header.

    error
        The HTTP error code to return to the client on failure.

    message
        A string to include in the response body on failure.

    """
    try:
        ref = cherrypy.serving.request.headers['Referer']
        match = bool(re.match(pattern, ref))
        if debug:
            cherrypy.log('Referer %r matches %r' % (ref, pattern),
                         'TOOLS.REFERER')
        if accept == match:
            return
    except KeyError:
        if debug:
            cherrypy.log('No Referer header', 'TOOLS.REFERER')
        if accept_missing:
            return

    raise cherrypy.HTTPError(error, message) 
Example #29
Source File: cptools.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def convert_params(exception=ValueError, error=400):
    """Convert request params based on function annotations, with error handling.

    exception
        Exception class to catch.

    status
        The HTTP error code to return to the client on failure.
    """
    request = cherrypy.serving.request
    types = request.handler.callable.__annotations__
    with cherrypy.HTTPError.handle(exception, error):
        for key in set(types).intersection(request.params):
            request.params[key] = types[key](request.params[key]) 
Example #30
Source File: cptools.py    From opsbro with MIT License 5 votes vote down vote up
def run(self):
        request = cherrypy.serving.request
        response = cherrypy.serving.response

        path = request.path_info
        if path.endswith('login_screen'):
            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()