本文整理汇总了Python中falcon.HTTPError方法的典型用法代码示例。如果您正苦于以下问题:Python falcon.HTTPError方法的具体用法?Python falcon.HTTPError怎么用?Python falcon.HTTPError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类falcon
的用法示例。
在下文中一共展示了falcon.HTTPError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: default_exception_handler
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import HTTPError [as 别名]
def default_exception_handler(ex, req, resp, params):
"""
Catch-all exception handler for standardized output.
If this is a standard falcon HTTPError, rethrow it for handling
"""
if isinstance(ex, falcon.HTTPError):
# allow the falcon http errors to bubble up and get handled
raise ex
else:
# take care of the uncaught stuff
exc_string = traceback.format_exc()
LOG.error('Unhanded Exception being handled: \n%s', exc_string)
format_error_resp(
req,
resp,
falcon.HTTP_500,
error_type=ex.__class__.__name__,
message="Unhandled Exception raised: %s" % str(ex),
retry=True)
示例2: default_exception_handler
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import HTTPError [as 别名]
def default_exception_handler(ex, req, resp, params):
"""
Catch-all exception handler for standardized output.
If this is a standard falcon HTTPError, rethrow it for handling
"""
if isinstance(ex, falcon.HTTPError):
# allow the falcon http errors to bubble up and get handled
raise ex
else:
# take care of the uncaught stuff
exc_string = traceback.format_exc()
logging.error('Unhanded Exception being handled: \n%s', exc_string)
format_error_resp(
req,
resp,
falcon.HTTP_500,
error_type=ex.__class__.__name__,
message="Unhandled Exception raised: %s" % str(ex),
retry=True
)
示例3: on_post
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import HTTPError [as 别名]
def on_post(self, request, response):
query = dict()
try:
raw_json = request.stream.read()
except Exception as e:
raise falcon.HTTPError(falcon.HTTP_400, 'Error', e.message)
try:
data = json.loads(raw_json, encoding='utf-8')
except ValueError:
raise falcon.HTTPError(falcon.HTTP_400, 'Malformed JSON')
if "id" not in data:
raise falcon.HTTPConflict('Task creation', "ID is not specified.")
if "type" not in data:
raise falcon.HTTPConflict('Task creation', "Type is not specified.")
transaction = self.client.push_task({ "task" : "vertex", "data" : data })
response.body = json.dumps({ "transaction" : transaction })
response.status = falcon.HTTP_202
示例4: on_get
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import HTTPError [as 别名]
def on_get(self, req, resp):
"""Handles GET requests"""
try:
mobile_number = '+{}'.format(req.get_param('mobile'))
otp = req.get_param('otp')
otp_data = OTPModel.select().where(OTPModel.mobile_number == mobile_number, OTPModel.otp == otp, OTPModel.is_verified == False)
if mobile_number and otp_data.exists():
otp_data = otp_data.get()
otp_data.is_verified = True
otp_data.save()
async_subscribe(mobile_number)
resp.media = {"message": "Congratulations!!! You have successfully subscribed for daily famous quote."}
elif mobile_number and not otp_data.exists():
async_send_otp(mobile_number)
resp.media = {"message": "An OTP verification has been sent on mobile {0}. To complete the subscription, Use OTP with this URL pattern https://quote-api.abdulwahid.info/subscribe?mobile={0}&otp=xxxx.".format(mobile_number)}
else:
raise falcon.HTTPError(falcon.HTTP_500, 'Require a valid mobile number as a query parameter. e.g https://<API_ENDPOINT>/subscribe?mobile=XXXXXXX')
except Exception as e:
raise falcon.HTTPError(falcon.HTTP_500, str(e))
开发者ID:PacktPublishing,项目名称:Building-Serverless-Python-Web-Services-with-Zappa,代码行数:21,代码来源:resources.py
示例5: on_post
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import HTTPError [as 别名]
def on_post(self, req, resp):
"""Handles POST requests"""
try:
file_object = req.get_param('file')
# file validation
if file_object.type != 'application/msword' or file_object.filename.split('.')[-1] != 'doc':
raise ValueError('Please provide a valid MS Office 93 -2003 document file.')
# calling _doc_to_text method from parser.py
text = doc_to_text(file_object)
quote = {
'text': text,
'filename': file_object.filename
}
resp.media = quote
except Exception as e:
raise falcon.HTTPError(falcon.HTTP_500, str(e))
开发者ID:PacktPublishing,项目名称:Building-Serverless-Python-Web-Services-with-Zappa,代码行数:20,代码来源:resources.py
示例6: on_post
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import HTTPError [as 别名]
def on_post(req, resp):
"""
Create user. Currently used only in debug mode.
"""
data = load_json_body(req)
connection = db.connect()
cursor = connection.cursor()
try:
cursor.execute('INSERT INTO `user` (`name`) VALUES (%(name)s)', data)
connection.commit()
except db.IntegrityError:
raise HTTPError('422 Unprocessable Entity',
'IntegrityError',
'user name "%(name)s" already exists' % data)
finally:
cursor.close()
connection.close()
resp.status = HTTP_201
示例7: on_post
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import HTTPError [as 别名]
def on_post(req, resp):
data = load_json_body(req)
new_role = data['name']
connection = db.connect()
cursor = connection.cursor()
try:
cursor.execute('INSERT INTO `role` (`name`) VALUES (%s)', new_role)
connection.commit()
except db.IntegrityError as e:
err_msg = str(e.args[1])
if 'Duplicate entry' in err_msg:
err_msg = 'role "%s" already existed' % new_role
raise HTTPError('422 Unprocessable Entity', 'IntegrityError', err_msg)
finally:
cursor.close()
connection.close()
resp.status = HTTP_201
示例8: on_post
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import HTTPError [as 别名]
def on_post(req, resp):
data = load_json_body(req)
connection = db.connect()
cursor = connection.cursor()
try:
cursor.execute('INSERT INTO `service` (`name`) VALUES (%(name)s)', data)
connection.commit()
except db.IntegrityError:
raise HTTPError('422 Unprocessable Entity',
'IntegrityError',
'service name "%(name)s" already exists' % data)
finally:
cursor.close()
connection.close()
resp.status = HTTP_201
示例9: default_exception_handler
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import HTTPError [as 别名]
def default_exception_handler(ex, req, resp, params):
"""
Catch-all exception handler for standardized output.
If this is a standard falcon HTTPError, rethrow it for handling
"""
if isinstance(ex, falcon.HTTPError):
# allow the falcon http errors to bubble up and get handled
raise ex
else:
# take care of the uncaught stuff
exc_string = traceback.format_exc()
logging.error('Unhandled Exception being handled: \n%s', exc_string)
format_error_resp(
req,
resp,
falcon.HTTP_500,
error_type=ex.__class__.__name__,
message="Unhandled Exception raised: %s" % str(ex),
retry=True
)
示例10: json_body
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import HTTPError [as 别名]
def json_body(req):
if not req.content_length:
return {}
try:
raw_json = req.stream.read()
except Exception:
raise freezer_api_exc.BadDataFormat('Empty request body. A valid '
'JSON document is required.')
try:
json_data = json.loads(raw_json, encoding='utf-8')
except ValueError:
raise falcon.HTTPError(falcon.HTTP_753,
'Malformed JSON')
return json_data
示例11: test_FreezerAPIException
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import HTTPError [as 别名]
def test_FreezerAPIException(self):
e = exceptions.FreezerAPIException(message='testing')
self.assertRaises(falcon.HTTPError,
e.handle, self.ex, self.mock_req, self.mock_req,
None)
示例12: test_DocumentNotFound
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import HTTPError [as 别名]
def test_DocumentNotFound(self):
e = exceptions.DocumentNotFound(message='testing')
self.assertRaises(falcon.HTTPError,
e.handle, self.ex, self.mock_req, self.mock_req,
None)
示例13: handle
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import HTTPError [as 别名]
def handle(ex, req, resp, params):
raise falcon.HTTPError(_('500 unknown server error'),
title=_("Internal Server Error"),
description=FreezerAPIException.message)
示例14: on_post
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import HTTPError [as 别名]
def on_post(self, request, response, vertex_id):
query = dict()
try:
raw_json = request.stream.read()
except Exception as e:
raise falcon.HTTPError(falcon.HTTP_400, 'Error', e.message)
try:
data = json.loads(raw_json, encoding='utf-8')
except ValueError:
raise falcon.HTTPError(falcon.HTTP_400, 'Malformed JSON')
data["id"] = vertex_id
try:
query = list(graph.query_vertices({ "id" : vertex_id }))
except Exception as e:
raise falcon.HTTPError(falcon.HTTP_400, 'Error', e.message)
if len(query) > 0:
raise falcon.HTTPConflict('Vertex Creation', "Vertex already exists.")
try:
result = graph.update_vertex(**data)
except Exception as e:
raise falcon.HTTPError(falcon.HTTP_400, 'Error', e.message)
response.status = falcon.HTTP_200
response.body = json.dumps({ "created" : result }, encoding='utf-8')
示例15: process_request
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import HTTPError [as 别名]
def process_request(self, req, resp):
self.set_access_control_allow_origin(resp)
body = req.stream.read()
if not body:
raise falcon.HTTPBadRequest('Empty request body',
'A valid JSON document is required.')
try:
req.context['_body'] = json.loads(
body.decode('utf-8'))
except (ValueError, UnicodeDecodeError):
raise falcon.HTTPError(
falcon.HTTP_753, 'Malformed JSON',
'JSON incorrect or not utf-8 encoded.')