本文整理匯總了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.')