當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。