本文整理汇总了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')
示例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
示例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)
示例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
示例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)
示例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)
示例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))
示例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)
示例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))
示例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)
示例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))
示例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'))
示例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
示例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)
示例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
}