当前位置: 首页>>代码示例>>Python>>正文


Python cherrypy.HTTPError方法代码示例

本文整理汇总了Python中cherrypy.HTTPError方法的典型用法代码示例。如果您正苦于以下问题:Python cherrypy.HTTPError方法的具体用法?Python cherrypy.HTTPError怎么用?Python cherrypy.HTTPError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cherrypy的用法示例。


在下文中一共展示了cherrypy.HTTPError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: set_response

# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
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) 
开发者ID:cherrypy,项目名称:cherrypy,代码行数:27,代码来源:_cperror.py

示例2: decode_entity

# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
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)
            ) 
开发者ID:cherrypy,项目名称:cherrypy,代码行数:18,代码来源:_cpreqbody.py

示例3: run

# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
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() 
开发者ID:cherrypy,项目名称:cherrypy,代码行数:27,代码来源:cptools.py

示例4: qvalue

# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
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 
开发者ID:cherrypy,项目名称:cherrypy,代码行数:19,代码来源:httputil.py

示例5: setup_server

# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
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) 
开发者ID:cherrypy,项目名称:cherrypy,代码行数:27,代码来源:test_etags.py

示例6: get_body

# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
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 
开发者ID:smarthomeNG,项目名称:smarthome,代码行数:24,代码来源:api_logics.py

示例7: get_body

# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
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 
开发者ID:smarthomeNG,项目名称:smarthome,代码行数:21,代码来源:api_plugin.py

示例8: save_scenes_config

# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
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) 
开发者ID:smarthomeNG,项目名称:smarthome,代码行数:23,代码来源:api_files.py

示例9: evalcheck

# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
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
    # 
开发者ID:smarthomeNG,项目名称:smarthome,代码行数:27,代码来源:api_services.py

示例10: yamlcheck

# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
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
    # 
开发者ID:smarthomeNG,项目名称:smarthome,代码行数:20,代码来源:api_services.py

示例11: sensors

# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
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 
开发者ID:Mirantis,项目名称:disk_perf_test_tool,代码行数:24,代码来源:webui.py

示例12: digest_auth

# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
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") 
开发者ID:naparuba,项目名称:opsbro,代码行数:22,代码来源:auth.py

示例13: run

# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
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 
开发者ID:naparuba,项目名称:opsbro,代码行数:26,代码来源:_cprequest.py

示例14: process_query_string

# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
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) 
开发者ID:naparuba,项目名称:opsbro,代码行数:20,代码来源:_cprequest.py

示例15: decode_entity

# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
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)
            ) 
开发者ID:morpheus65535,项目名称:bazarr,代码行数:18,代码来源:_cpreqbody.py


注:本文中的cherrypy.HTTPError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。