當前位置: 首頁>>代碼示例>>Python>>正文


Python falcon.HTTPInternalServerError方法代碼示例

本文整理匯總了Python中falcon.HTTPInternalServerError方法的典型用法代碼示例。如果您正苦於以下問題:Python falcon.HTTPInternalServerError方法的具體用法?Python falcon.HTTPInternalServerError怎麽用?Python falcon.HTTPInternalServerError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在falcon的用法示例。


在下文中一共展示了falcon.HTTPInternalServerError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: on_get

# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPInternalServerError [as 別名]
def on_get(self, req, resp, ical_key):
        """Access the oncall calendar identified by the key.

        The response is in ical format and this url is intended to be
        supplied to any calendar application that can subscribe to
        calendars from the internet.
        """
        try:
            path = self.base_url + '/api/v0/ical/' + ical_key
            if req.query_string:
                path += '?%s' % req.query_string
            result = self.oncall_client.get(path)
        except MaxRetryError as ex:
            logger.error(ex)
        else:
            if result.status_code == 200:
                resp.status = falcon.HTTP_200
                resp.content_type = result.headers['Content-Type']
                resp.body = result.content
                return
            elif 400 <= result.status_code <= 499:
                resp.status = falcon.HTTP_404
                return

        raise falcon.HTTPInternalServerError('Internal Server Error', 'Invalid response from API') 
開發者ID:linkedin,項目名稱:iris-relay,代碼行數:27,代碼來源:app.py

示例2: on_post

# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPInternalServerError [as 別名]
def on_post(self, req, resp):
        """
        Accept twilio POST that has message delivery status, and pass it
        to iris-api
        """

        try:
            re = self.iclient.post(self.endpoint, req.context['body'].decode('utf-8'), raw=True)
        except MaxRetryError:
            logger.exception('Failed posting data to iris-api')
            raise falcon.HTTPInternalServerError('Internal Server Error', 'API call failed')

        if re.status != 204:
            logger.error('Invalid response from API for delivery status update: %s', re.status)
            raise falcon.HTTPBadRequest('Likely bad params passed', 'Invalid response from API')

        resp.status = falcon.HTTP_204 
開發者ID:linkedin,項目名稱:iris-relay,代碼行數:19,代碼來源:app.py

示例3: default_exception_handler

# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPInternalServerError [as 別名]
def default_exception_handler(ex, req, resp, params):
    if hasattr(ex, 'title') and "Failed data validation" in ex.title:
        JsonSchemaException(ex)
    message = "Unexpected error occurred: {}".format(ex)
    logger.error(message + "\nRequest: {}  Params: {}".format(req, params))

    if isinstance(ex, falcon.HTTPUnauthorized):
        raise ex

    if isinstance(ex, falcon.HTTPForbidden):
        raise ex

    stacktrace = traceback.format_exc()
    logger.error(stacktrace)

    raise falcon.HTTPInternalServerError(message) 
開發者ID:IntelAI,項目名稱:inference-model-manager,代碼行數:18,代碼來源:errors_handling.py

示例4: __call__

# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPInternalServerError [as 別名]
def __call__(self, req, resp):
        path = self.base_url + '/v0/' + '/'.join(req.path.split('/')[4:])
        if req.query_string:
            path += '?%s' % req.query_string
        try:
            if req.method == 'POST':
                body = b''
                if req.context['body']:
                    body = req.context['body']
                result = self.iris_client.post(path, body)
            elif req.method == 'GET':
                result = self.iris_client.get(path)
            elif req.method == 'OPTIONS':
                return
            else:
                raise falcon.HTTPMethodNotAllowed(['GET', 'POST', 'PUT', 'DELETE'])
        except MaxRetryError as e:
            logger.error(e.reason)
            raise falcon.HTTPInternalServerError('Internal Server Error', 'Max retry error, api unavailable')
        if result.status_code == 400:
            raise falcon.HTTPBadRequest('Bad Request', '')
        elif str(result.status_code)[0] != '2':
            raise falcon.HTTPInternalServerError('Internal Server Error', 'Unknown response from the api')
        else:
            resp.status = falcon.HTTP_200
            resp.content_type = result.headers['Content-Type']
            resp.body = result.content 
開發者ID:linkedin,項目名稱:iris-relay,代碼行數:29,代碼來源:app.py

示例5: test_StorageEngineError

# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPInternalServerError [as 別名]
def test_StorageEngineError(self):
        e = exceptions.StorageEngineError(message='testing')
        self.assertRaises(falcon.HTTPInternalServerError,
                          e.handle, self.ex, self.mock_req, self.mock_req,
                          None) 
開發者ID:openstack,項目名稱:freezer-api,代碼行數:7,代碼來源:test_exceptions.py

示例6: handle

# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPInternalServerError [as 別名]
def handle(ex, req, resp, params):
        raise falcon.HTTPInternalServerError(
            title=_("Internal Storage Error"),
            description=ex.message) 
開發者ID:openstack,項目名稱:freezer-api,代碼行數:6,代碼來源:exceptions.py

示例7: on_get

# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPInternalServerError [as 別名]
def on_get(self, req, resp):
        try:
            output = list(MODELS)
            resp.body = json.dumps(output, sort_keys=True, indent=2)
            resp.content_type = 'text/string'
            resp.append_header('Access-Control-Allow-Origin', "*")
            resp.status = falcon.HTTP_200
        except Exception as e:
            raise falcon.HTTPInternalServerError(
                'Models retrieval failed',
                '{}'.format(e)) 
開發者ID:jgontrum,項目名稱:spacy-api-docker,代碼行數:13,代碼來源:server.py

示例8: form_response

# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPInternalServerError [as 別名]
def form_response(self, message):
        if self.k8s_api_exception.status == 403:
            raise falcon.HTTPForbidden(message)
        elif 400 <= self.k8s_api_exception.status < 500:
            raise falcon.HTTPBadRequest(message)
        else:
            raise falcon.HTTPInternalServerError(message) 
開發者ID:IntelAI,項目名稱:inference-model-manager,代碼行數:9,代碼來源:errors_handling.py

示例9: handler

# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPInternalServerError [as 別名]
def handler(ex, req, resp, params):
        logger.error(str(ex))
        raise falcon.HTTPInternalServerError(str(ex)) 
開發者ID:IntelAI,項目名稱:inference-model-manager,代碼行數:5,代碼來源:errors_handling.py

示例10: process

# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPInternalServerError [as 別名]
def process(self, req, resp):
        if req.method == 'OPTIONS':
            if self.cors_origin is not False:
                self.process_preflight_request(req, resp)
            response_body = '\n'

            response_body += 'nothing here\n\n'

            resp.body = response_body
            resp.status = falcon.HTTP_200
            return
        try:
            if self.cors_origin is not False:
                self.process_preflight_request(req, resp)
            self.dispatch(req, resp)
        except Exception as e:
            self.log.error_trace('process failed')
            error_type = type(e)
            error_map = {
                falcon.errors.HTTPNotFound: http_falcon_handler,
                falcon.errors.HTTPMissingParam: http_falcon_handler,
                falcon.errors.HTTPInvalidParam: http_falcon_handler,
                falcon.errors.HTTPInternalServerError: http_falcon_handler,
            }
            if self.custom_error_map:
                error_map.update(self.custom_error_map)

            error_func = error_map.get(error_type)
            if error_func:
                error_func(req, resp, e)
            else:
                default_error_handler(req, resp, e) 
開發者ID:pingf,項目名稱:falsy,代碼行數:34,代碼來源:swagger_server.py

示例11: __init__

# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPInternalServerError [as 別名]
def __init__(self):
        try:
            super(Metrics, self).__init__()
            self._region = cfg.CONF.region
            self._message_queue = simport.load(cfg.CONF.messaging.driver)(
                'metrics')
            self._metrics_repo = simport.load(
                cfg.CONF.repositories.metrics_driver)()
            self._batch_size = cfg.CONF.kafka.queue_buffering_max_messages

        except Exception as ex:
            LOG.exception(ex)
            raise falcon.HTTPInternalServerError('Service unavailable',
                                                 str(ex)) 
開發者ID:openstack,項目名稱:monasca-api,代碼行數:16,代碼來源:metrics.py

示例12: send_event

# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPInternalServerError [as 別名]
def send_event(self, message_queue, event_msg):
        try:
            message_queue.send_message(helpers.to_json(event_msg))
        except message_queue_exceptions.MessageQueueException as ex:
            LOG.exception(ex)
            raise falcon.HTTPInternalServerError(
                'Message queue service unavailable'.encode('utf8'),
                str(ex).encode('utf8')) 
開發者ID:openstack,項目名稱:monasca-api,代碼行數:10,代碼來源:alarming.py

示例13: resource_try_catch_block

# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPInternalServerError [as 別名]
def resource_try_catch_block(fun):
    def try_it(*args, **kwargs):
        try:
            return fun(*args, **kwargs)

        except falcon.HTTPError:
            raise

        except exceptions.DoesNotExistException:
            raise falcon.HTTPNotFound

        except exceptions.MultipleMetricsException as ex:
            raise falcon.HTTPConflict("MultipleMetrics", str(ex))

        except exceptions.AlreadyExistsException as ex:
            raise falcon.HTTPConflict(ex.__class__.__name__, str(ex))

        except exceptions.InvalidUpdateException as ex:
            raise HTTPUnprocessableEntityError(ex.__class__.__name__, str(ex))

        except exceptions.RepositoryException as ex:
            LOG.exception(ex)
            msg = " ".join(map(str, ex.args[0].args))
            raise falcon.HTTPInternalServerError('The repository was unable '
                                                 'to process your request',
                                                 msg)

        except Exception as ex:
            LOG.exception(ex)
            raise falcon.HTTPInternalServerError('Service unavailable',
                                                 str(ex))

    return try_it 
開發者ID:openstack,項目名稱:monasca-api,代碼行數:35,代碼來源:resource.py

示例14: on_get

# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPInternalServerError [as 別名]
def on_get(self, req, resp, profile, suggested_filename):
        router = [j[0] for j in authority.list_signed(
            common_name=config.cp2.get(profile, "router"))][0]
        subnets = set([ip_network(j) for j in config.cp2.get(profile, "subnets").replace(",", " ").split(" ")])
        model = config.cp2.get(profile, "model")
        build_script_path = config.cp2.get(profile, "command")
        overlay_path = config.cp2.get(profile, "overlay")
        site_script_path = config.cp2.get(profile, "script")
        suffix = config.cp2.get(profile, "filename")

        build = "/var/lib/certidude/builder/" + profile
        log_path = build + "/build.log"
        if not os.path.exists(build + "/overlay/etc/uci-defaults"):
            os.makedirs(build + "/overlay/etc/uci-defaults")
        os.system("rsync -av " + overlay_path + "/ " + build + "/overlay/")

        if site_script_path:
            template = Template(open(site_script_path).read())
            with open(build + "/overlay/etc/uci-defaults/99-site-config", "w") as fh:
                fh.write(template.render(authority_name=const.FQDN))

        proc = subprocess.Popen(("/bin/bash", build_script_path),
            stdout=open(log_path, "w"), stderr=subprocess.STDOUT,
            close_fds=True, shell=False,
            cwd=os.path.dirname(os.path.realpath(build_script_path)),
            env={"PROFILE": model, "PATH":"/usr/sbin:/usr/bin:/sbin:/bin",
                "ROUTER": router,
                "IKE": config.cp2.get(profile, "ike"),
                "ESP": config.cp2.get(profile, "esp"),
                "SUBNETS": ",".join(str(j) for j in subnets),
                "AUTHORITY_CERTIFICATE_ALGORITHM": authority.public_key.algorithm,
                "AUTHORITY_CERTIFICATE_DISTINGUISHED_NAME": cert_to_dn(authority.certificate),
                "BUILD":build, "OVERLAY":build + "/overlay/"},
            startupinfo=None, creationflags=0)
        proc.communicate()
        if proc.returncode:
            logger.info("Build script finished with non-zero exitcode, see %s for more information" % log_path)
            raise falcon.HTTPInternalServerError("Build script finished with non-zero exitcode")

        for dname in os.listdir(build):
            if dname.startswith("openwrt-imagebuilder-") and ".tar." not in dname:
                subdir = os.path.join(build, dname, "bin", "targets")
                for root, dirs, files in os.walk(subdir):
                    for filename in files:
                        if filename.endswith(suffix):
                            path = os.path.join(root, filename)
                            click.echo("Serving: %s" % path)
                            resp.body = open(path, "rb").read()
                            resp.set_header("Content-Disposition", ("attachment; filename=%s" % suggested_filename))
                            return
                raise falcon.HTTPNotFound(description="Couldn't find file ending with '%s' in directory %s" % (suffix, subdir))
        raise falcon.HTTPNotFound(description="Failed to find image builder directory in %s" % build) 
開發者ID:laurivosandi,項目名稱:certidude,代碼行數:54,代碼來源:builder.py

示例15: on_post

# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPInternalServerError [as 別名]
def on_post(self, req: falcon.Request, resp: falcon.Response) -> None:
        """
        Evaluate Python code and return stdout, stderr, and the return code.

        The return codes mostly resemble those of a Unix shell. Some noteworthy cases:

        - None
            The NsJail process failed to launch
        - 137 (SIGKILL)
            Typically because NsJail killed the Python process due to time or memory constraints
        - 255
            NsJail encountered a fatal error

        Request body:

        >>> {
        ...     "input": "print(1 + 1)"
        ... }

        Response format:

        >>> {
        ...     "stdout": "2\\n",
        ...     "returncode": 0
        ... }

        Status codes:

        - 200
            Successful evaluation; not indicative that the input code itself works
        - 400
           Input's JSON schema is invalid
        - 415
            Unsupported content type; only application/JSON is supported
        """
        code = req.media["input"]

        try:
            result = self.nsjail.python3(code)
        except Exception:
            log.exception("An exception occurred while trying to process the request")
            raise falcon.HTTPInternalServerError

        resp.media = {
            "stdout": result.stdout,
            "returncode": result.returncode
        } 
開發者ID:python-discord,項目名稱:snekbox,代碼行數:49,代碼來源:eval.py


注:本文中的falcon.HTTPInternalServerError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。