本文整理匯總了Python中webapp2.HTTPException方法的典型用法代碼示例。如果您正苦於以下問題:Python webapp2.HTTPException方法的具體用法?Python webapp2.HTTPException怎麽用?Python webapp2.HTTPException使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類webapp2
的用法示例。
在下文中一共展示了webapp2.HTTPException方法的6個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: dispatcher
# 需要導入模塊: import webapp2 [as 別名]
# 或者: from webapp2 import HTTPException [as 別名]
def dispatcher(router, request, response):
try:
if uwsgi is not None:
uwsgi.set_logvar('request_id', request.id)
except: # pylint: disable=bare-except
request.logger.error("Error setting request_id log var", exc_info=True)
collect_endpoint(request)
try:
rv = router.default_dispatcher(request, response)
if rv is not None:
response.write(json.dumps(rv, default=encoder.custom_json_serializer))
response.headers['Content-Type'] = 'application/json; charset=utf-8'
except webapp2.HTTPException as e:
util.send_json_http_exception(response, str(e), e.code, request.id)
except Exception as e: # pylint: disable=broad-except
request.logger.error("Error dispatching request", exc_info=True)
if config.get_item('core', 'debug'):
message = traceback.format_exc()
else:
message = 'Internal Server Error'
util.send_json_http_exception(response, message, 500, request.id)
示例2: handle_exception
# 需要導入模塊: import webapp2 [as 別名]
# 或者: from webapp2 import HTTPException [as 別名]
def handle_exception(self, exception, debug):
logging.exception(exception)
status_code = 500
if isinstance(exception, webapp2.HTTPException):
status_code = exception.code
self.failed_response(status_code, {
'errors': [self.__format_error(exception)]
})
示例3: _instrumented_dispatcher
# 需要導入模塊: import webapp2 [as 別名]
# 或者: from webapp2 import HTTPException [as 別名]
def _instrumented_dispatcher(dispatcher, request, response, time_fn=time.time):
start_time = time_fn()
response_status = 0
flush_thread = None
time_now = time_fn()
if need_to_flush_metrics(time_now):
flush_thread = threading.Thread(target=_flush_metrics, args=(time_now,))
flush_thread.start()
try:
ret = dispatcher(request, response)
except webapp2.HTTPException as ex:
response_status = ex.code
raise
except Exception:
response_status = 500
raise
else:
if isinstance(ret, webapp2.Response):
response = ret
response_status = response.status_int
finally:
if flush_thread:
flush_thread.join()
elapsed_ms = int((time_fn() - start_time) * 1000)
# Use the route template regex, not the request path, to prevent an
# explosion in possible field values.
name = request.route.template if request.route is not None else ''
http_metrics.update_http_server_metrics(
name, response_status, elapsed_ms,
request_size=request.content_length,
response_size=response.content_length,
user_agent=request.user_agent)
return ret
示例4: handle_exception
# 需要導入模塊: import webapp2 [as 別名]
# 或者: from webapp2 import HTTPException [as 別名]
def handle_exception(self, exception, debug):
# Log the error.
logging.critical('BaseHandler exception', exc_info=exception)
# Set a custom message.
if hasattr(exception, 'detail') and getattr(exception, 'detail'):
self.response.write(getattr(exception, 'detail'))
# If the exception is a HTTPException, use its error code.
# Otherwise use a generic 500 error code.
if isinstance(exception, webapp2.HTTPException):
self.response.set_status(exception.code)
else:
self.response.set_status(500)
示例5: handle_exception
# 需要導入模塊: import webapp2 [as 別名]
# 或者: from webapp2 import HTTPException [as 別名]
def handle_exception(self, exception, unused_debug_mode):
"""Handle any uncaught exceptions.
Args:
exception: The exception that was thrown.
unused_debug_mode: True if the application is running in debug mode.
"""
# Default to a 500.
http_status = httplib.INTERNAL_SERVER_ERROR
# Calls to abort() raise a child class of HTTPException, so extract the
# HTTP status and explanation if possible.
if isinstance(exception, webapp2.HTTPException):
http_status = getattr(exception, 'code', httplib.INTERNAL_SERVER_ERROR)
# Write out the exception's explanation to the response body
escaped_explanation = _HtmlEscape(str(exception))
self.response.write(escaped_explanation)
# If the RequestHandler has a corresponding request counter, increment it.
if self.RequestCounter is not None:
self.RequestCounter.Increment(http_status)
# If the exception occurs within a unit test, make sure the stacktrace is
# easily discerned from the console.
if not env_utils.RunningInProd():
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
# Set the response code and log the exception regardless.
self.response.set_status(http_status)
logging.exception(exception)
示例6: handle_exception
# 需要導入模塊: import webapp2 [as 別名]
# 或者: from webapp2 import HTTPException [as 別名]
def handle_exception(self, exception, debug, return_json=False): # pylint: disable=arguments-differ
"""
Send JSON response for exception
For HTTP and other known exceptions, use its error code
For all others use a generic 500 error code and log the stack trace
"""
request_id = self.request.id
custom_errors = None
message = str(exception)
if isinstance(exception, webapp2.HTTPException):
code = exception.code
elif isinstance(exception, errors.InputValidationException):
code = 400
elif isinstance(exception, errors.APIAuthProviderException):
code = 401
elif isinstance(exception, errors.APIRefreshTokenException):
code = 401
custom_errors = exception.errors
elif isinstance(exception, errors.APIUnknownUserException):
code = 402
elif isinstance(exception, errors.APIConsistencyException):
code = 400
elif isinstance(exception, errors.APIPermissionException):
custom_errors = exception.errors
code = 403
elif isinstance(exception, errors.APINotFoundException):
code = 404
elif isinstance(exception, errors.APIConflictException):
code = 409
elif isinstance(exception, errors.APIValidationException):
code = 422
custom_errors = exception.errors
elif isinstance(exception, errors.FileStoreException):
code = 400
elif isinstance(exception, errors.FileFormException):
code = 400
elif isinstance(exception, errors.FileFormException):
code = 400
elif isinstance(exception, ElasticsearchException):
code = 503
message = "Search is currently down. Try again later."
self.request.logger.error(traceback.format_exc())
elif isinstance(exception, KeyError):
code = 500
message = "Key {} was not found".format(str(exception))
else:
code = 500
if code == 500:
tb = traceback.format_exc()
self.request.logger.error(tb)
if return_json:
return util.create_json_http_exception_response(message, code, request_id, custom=custom_errors)
util.send_json_http_exception(self.response, message, code, request_id, custom=custom_errors)