def _handle_exception():
"""Print exceptions raised by subscribers to stderr."""
# Heavily influenced by logging.Handler.handleError.
# See note here:
# https://docs.python.org/3.4/library/sys.html#sys.__stderr__
if sys.stderr:
einfo = sys.exc_info()
try:
traceback.print_exception(einfo[0], einfo[1], einfo[2],
None, sys.stderr)
except IOError:
pass
finally:
del einfo
# Note - to avoid bugs from forgetting which if these is all lowercase and
# which are camelCase, and at the same time avoid having to add a test for
# every command, use all lowercase here and test against command_name.lower().
python类html()的实例源码
def _emit(self, record):
# If there's no exception being processed,
# exc_info may be a 3-tuple of None
# http://docs.python.org/library/sys.html#sys.exc_info
if record.exc_info is True or (record.exc_info and all(record.exc_info)):
handler = self.client.get_handler('elasticapm.events.Exception')
exception = handler.capture(self.client, exc_info=record.exc_info)
else:
exception = None
return self.client.capture_message(
param_message={
'message': record.msg,
'params': record.args
},
exception=exception,
level=LOOKBOOK_LEVELS[record.level],
logger_name=record.channel,
custom=record.extra,
)
def load_wsgi(self):
try:
self.wsgi = self.app.wsgi()
except SyntaxError as e:
if not self.cfg.reload:
raise
self.log.exception(e)
# fix from PR #1228
# storing the traceback into exc_tb will create a circular reference.
# per https://docs.python.org/2/library/sys.html#sys.exc_info warning,
# delete the traceback after use.
try:
exc_type, exc_val, exc_tb = sys.exc_info()
self.reloader.add_extra_file(exc_val.filename)
tb_string = traceback.format_tb(exc_tb)
self.wsgi = util.make_fail_app(tb_string)
finally:
del exc_tb
def load_wsgi(self):
try:
self.wsgi = self.app.wsgi()
except SyntaxError as e:
if self.cfg.reload == 'off':
raise
self.log.exception(e)
# fix from PR #1228
# storing the traceback into exc_tb will create a circular reference.
# per https://docs.python.org/2/library/sys.html#sys.exc_info warning,
# delete the traceback after use.
try:
exc_type, exc_val, exc_tb = sys.exc_info()
self.reloader.add_extra_file(exc_val.filename)
tb_string = six.StringIO()
traceback.print_tb(exc_tb, file=tb_string)
self.wsgi = util.make_fail_app(tb_string.getvalue())
finally:
del exc_tb
def create_document_from_row_list(title, header, row_list,
file_path, is_landscape = False):
"""Create and save PDF document from a table.
Args:
title: The title that will be used on the first page of the document.
row_list: List of rows containing the data
file_path: full path of the pdf document to save
"""
options = {
'page-size': 'Letter',
'encoding': "UTF-8"
}
if (is_landscape):
options["orientation"] = 'Landscape'
pdfkit.from_string(
html.generate_document_from_row_list(
title, header, row_list).encode('unicode-escape'),
file_path,
options
)
def load_wsgi(self):
try:
self.wsgi = self.app.wsgi()
except SyntaxError as e:
if not self.cfg.reload:
raise
self.log.exception(e)
# fix from PR #1228
# storing the traceback into exc_tb will create a circular reference.
# per https://docs.python.org/2/library/sys.html#sys.exc_info warning,
# delete the traceback after use.
try:
exc_type, exc_val, exc_tb = sys.exc_info()
self.reloader.add_extra_file(exc_val.filename)
tb_string = traceback.format_tb(exc_tb)
self.wsgi = util.make_fail_app(tb_string)
finally:
del exc_tb
def load_wsgi(self):
try:
self.wsgi = self.app.wsgi()
except SyntaxError as e:
if not self.cfg.reload:
raise
self.log.exception(e)
# fix from PR #1228
# storing the traceback into exc_tb will create a circular reference.
# per https://docs.python.org/2/library/sys.html#sys.exc_info warning,
# delete the traceback after use.
try:
exc_type, exc_val, exc_tb = sys.exc_info()
self.reloader.add_extra_file(exc_val.filename)
tb_string = traceback.format_tb(exc_tb)
self.wsgi = util.make_fail_app(tb_string)
finally:
del exc_tb
def _handle_exception():
"""Print exceptions raised by subscribers to stderr."""
# Heavily influenced by logging.Handler.handleError.
# See note here:
# https://docs.python.org/3.4/library/sys.html#sys.__stderr__
if sys.stderr:
einfo = sys.exc_info()
try:
traceback.print_exception(einfo[0], einfo[1], einfo[2],
None, sys.stderr)
except IOError:
pass
finally:
del einfo
# Note - to avoid bugs from forgetting which if these is all lowercase and
# which are camelCase, and at the same time avoid having to add a test for
# every command, use all lowercase here and test against command_name.lower().
def load_wsgi(self):
try:
self.wsgi = self.app.wsgi()
except SyntaxError as e:
if not self.cfg.reload:
raise
self.log.exception(e)
# fix from PR #1228
# storing the traceback into exc_tb will create a circular reference.
# per https://docs.python.org/2/library/sys.html#sys.exc_info warning,
# delete the traceback after use.
try:
exc_type, exc_val, exc_tb = sys.exc_info()
self.reloader.add_extra_file(exc_val.filename)
tb_string = traceback.format_tb(exc_tb)
self.wsgi = util.make_fail_app(tb_string)
finally:
del exc_tb
def load_wsgi(self):
try:
self.wsgi = self.app.wsgi()
except SyntaxError as e:
if not self.cfg.reload:
raise
self.log.exception(e)
# fix from PR #1228
# storing the traceback into exc_tb will create a circular reference.
# per https://docs.python.org/2/library/sys.html#sys.exc_info warning,
# delete the traceback after use.
try:
exc_type, exc_val, exc_tb = sys.exc_info()
self.reloader.add_extra_file(exc_val.filename)
tb_string = traceback.format_tb(exc_tb)
self.wsgi = util.make_fail_app(tb_string)
finally:
del exc_tb
def load_wsgi(self):
try:
self.wsgi = self.app.wsgi()
except SyntaxError as e:
if not self.cfg.reload:
raise
self.log.exception(e)
# fix from PR #1228
# storing the traceback into exc_tb will create a circular reference.
# per https://docs.python.org/2/library/sys.html#sys.exc_info warning,
# delete the traceback after use.
try:
exc_type, exc_val, exc_tb = sys.exc_info()
self.reloader.add_extra_file(exc_val.filename)
tb_string = traceback.format_tb(exc_tb)
self.wsgi = util.make_fail_app(tb_string)
finally:
del exc_tb
def load_wsgi(self):
try:
self.wsgi = self.app.wsgi()
except SyntaxError as e:
if not self.cfg.reload:
raise
self.log.exception(e)
# fix from PR #1228
# storing the traceback into exc_tb will create a circular reference.
# per https://docs.python.org/2/library/sys.html#sys.exc_info warning,
# delete the traceback after use.
try:
exc_type, exc_val, exc_tb = sys.exc_info()
self.reloader.add_extra_file(exc_val.filename)
tb_string = traceback.format_tb(exc_tb)
self.wsgi = util.make_fail_app(tb_string)
finally:
del exc_tb
def _handle_exception():
"""Print exceptions raised by subscribers to stderr."""
# Heavily influenced by logging.Handler.handleError.
# See note here:
# https://docs.python.org/3.4/library/sys.html#sys.__stderr__
if sys.stderr:
einfo = sys.exc_info()
try:
traceback.print_exception(einfo[0], einfo[1], einfo[2],
None, sys.stderr)
except IOError:
pass
finally:
del einfo
# Note - to avoid bugs from forgetting which if these is all lowercase and
# which are camelCase, and at the same time avoid having to add a test for
# every command, use all lowercase here and test against command_name.lower().
def load_wsgi(self):
try:
self.wsgi = self.app.wsgi()
except SyntaxError as e:
if self.cfg.reload == 'off':
raise
self.log.exception(e)
# fix from PR #1228
# storing the traceback into exc_tb will create a circular reference.
# per https://docs.python.org/2/library/sys.html#sys.exc_info warning,
# delete the traceback after use.
try:
exc_type, exc_val, exc_tb = sys.exc_info()
self.reloader.add_extra_file(exc_val.filename)
tb_string = six.StringIO()
traceback.print_tb(exc_tb, file=tb_string)
self.wsgi = util.make_fail_app(tb_string.getvalue())
finally:
del exc_tb
def load_wsgi(self):
try:
self.wsgi = self.app.wsgi()
except SyntaxError as e:
if not self.cfg.reload:
raise
self.log.exception(e)
# fix from PR #1228
# storing the traceback into exc_tb will create a circular reference.
# per https://docs.python.org/2/library/sys.html#sys.exc_info warning,
# delete the traceback after use.
try:
exc_type, exc_val, exc_tb = sys.exc_info()
self.reloader.add_extra_file(exc_val.filename)
tb_string = traceback.format_tb(exc_tb)
self.wsgi = util.make_fail_app(tb_string)
finally:
del exc_tb
def _handle_exception():
"""Print exceptions raised by subscribers to stderr."""
# Heavily influenced by logging.Handler.handleError.
# See note here:
# https://docs.python.org/3.4/library/sys.html#sys.__stderr__
if sys.stderr:
einfo = sys.exc_info()
try:
traceback.print_exception(einfo[0], einfo[1], einfo[2],
None, sys.stderr)
except IOError:
pass
finally:
del einfo
# Note - to avoid bugs from forgetting which if these is all lowercase and
# which are camelCase, and at the same time avoid having to add a test for
# every command, use all lowercase here and test against command_name.lower().
def _handle_exception():
"""Print exceptions raised by subscribers to stderr."""
# Heavily influenced by logging.Handler.handleError.
# See note here:
# https://docs.python.org/3.4/library/sys.html#sys.__stderr__
if sys.stderr:
einfo = sys.exc_info()
try:
traceback.print_exception(einfo[0], einfo[1], einfo[2],
None, sys.stderr)
except IOError:
pass
finally:
del einfo
# Note - to avoid bugs from forgetting which if these is all lowercase and
# which are camelCase, and at the same time avoid having to add a test for
# every command, use all lowercase here and test against command_name.lower().
def load_wsgi(self):
try:
self.wsgi = self.app.wsgi()
except SyntaxError as e:
if not self.cfg.reload:
raise
self.log.exception(e)
# fix from PR #1228
# storing the traceback into exc_tb will create a circular reference.
# per https://docs.python.org/2/library/sys.html#sys.exc_info warning,
# delete the traceback after use.
try:
exc_type, exc_val, exc_tb = sys.exc_info()
self.reloader.add_extra_file(exc_val.filename)
tb_string = traceback.format_tb(exc_tb)
self.wsgi = util.make_fail_app(tb_string)
finally:
del exc_tb
def __init__(self, message=None):
super(WhichException, self).__init__(message)
# See: https://docs.python.org/2/library/sys.html#sys.platform
def __init__(self):
self.__index = None
self.py_tag = 'cpython-%s%s' % sys.version_info[:2]
"""
Short name for distinguish Python implementations and versions.
It's like `sys.implementation.cache_tag` but for Python < 3.3
we generate something similar. See:
http://docs.python.org/3/library/sys.html#sys.implementation
.. todo:: Detect interpreter (e.g., PyPy).
"""
def __init__(self):
self.__index = None
self.py_tag = 'cpython-%s%s' % sys.version_info[:2]
"""
Short name for distinguish Python implementations and versions.
It's like `sys.implementation.cache_tag` but for Python < 3.3
we generate something similar. See:
http://docs.python.org/3/library/sys.html#sys.implementation
.. todo:: Detect interpreter (e.g., PyPy).
"""
def generate_document_from_row_list(title, header, row_list):
"""Create HTML5 document from a table.
Args:
title: Title of html document.
row_list: Table with the data to generate the document.
"""
doc, tag, text = Doc().tagtext()
doc.asis("<!DOCTYPE html>")
with tag("html"):
with tag("head"):
doc.asis("<meta charset=\"utf-8\">")
with tag("title"):
text(title)
with tag("body"):
with tag("h1"):
text(title)
if (header is not None):
with tag("h3"):
text(header)
with tag("table", border="1"):
for r in row_list:
num_cols = len(r)
with tag("tr"):
for i in range(num_cols):
with tag("td"):
if r[i] is None:
text("")
elif unicode(r[i]).encode(
"unicode-escape").startswith("<img"):
doc.asis(r[i])
else:
text(r[i])
return doc.getvalue()
def _handle_exception():
"""Print exceptions raised by subscribers to stderr."""
# Heavily influenced by logging.Handler.handleError.
# See note here:
# https://docs.python.org/3.4/library/sys.html#sys.__stderr__
if sys.stderr:
einfo = sys.exc_info()
try:
traceback.print_exception(einfo[0], einfo[1], einfo[2],
None, sys.stderr)
except IOError:
pass
finally:
del einfo
def open_dir_cmd():
# https://docs.python.org/2/library/sys.html#sys.platform
if sys.platform == 'win32':
return 'start'
elif sys.platform == 'darwin':
return 'open'
else:
return 'xdg-open'
def __init__(self):
self.__index = None
self.py_tag = 'cpython-%s%s' % sys.version_info[:2]
"""
Short name for distinguish Python implementations and versions.
It's like `sys.implementation.cache_tag` but for Python < 3.3
we generate something similar. See:
http://docs.python.org/3/library/sys.html#sys.implementation
.. todo:: Detect interpreter (e.g., PyPy).
"""
def handle_exception(ex):
# For error code, follow guidelines at https://docs.python.org/2/library/sys.html#sys.exit,
from msrestazure.azure_exceptions import CloudError
if isinstance(ex, (CLIError, CloudError)):
logger.error(ex.args[0])
return ex.args[1] if len(ex.args) >= 2 else 1
elif isinstance(ex, KeyboardInterrupt):
return 1
logger.exception(ex)
return 1
def _handle_exception():
"""Print exceptions raised by subscribers to stderr."""
# Heavily influenced by logging.Handler.handleError.
# See note here:
# https://docs.python.org/3.4/library/sys.html#sys.__stderr__
if sys.stderr:
einfo = sys.exc_info()
try:
traceback.print_exception(einfo[0], einfo[1], einfo[2],
None, sys.stderr)
except IOError:
pass
finally:
del einfo
def _install_import_hooks(config, path_override_hook):
"""Install runtime's import hooks.
These hooks customize the import process as per
https://docs.python.org/2/library/sys.html#sys.meta_path .
Args:
config: An apphosting/tools/devappserver2/runtime_config.proto
for this instance.
path_override_hook: A hook for importing special appengine
versions of select libraries from the libraries
section of the current module's app.yaml file.
"""
if not config.vm:
enabled_library_regexes = [
NAME_TO_CMODULE_WHITELIST_REGEX[lib.name] for lib in config.libraries
if lib.name in NAME_TO_CMODULE_WHITELIST_REGEX]
sys.meta_path = [
StubModuleImportHook(),
ModuleOverrideImportHook(_MODULE_OVERRIDE_POLICIES),
CModuleImportHook(enabled_library_regexes),
path_override_hook,
PyCryptoRandomImportHook,
PathRestrictingImportHook(enabled_library_regexes)]
else:
sys.meta_path = [
# Picks up custom versions of certain libraries in the libraries section
# of app.yaml
path_override_hook,
# Picks up a custom version of Crypto.Random.OSRNG.posix.
# TODO: Investigate removing this as it may not be needed
# for vms since they are able to read /dev/urandom, I left it for
# consistency.
PyCryptoRandomImportHook]
def __init__(self):
self.__index = None
self.py_tag = 'cpython-%s%s' % sys.version_info[:2]
"""
Short name for distinguish Python implementations and versions.
It's like `sys.implementation.cache_tag` but for Python < 3.3
we generate something similar. See:
http://docs.python.org/3/library/sys.html#sys.implementation
.. todo:: Detect interpreter (e.g., PyPy).
"""
def exc_str(exc=None, limit=None):
"""Enhanced str for exceptions. Should include original location
Parameters
----------
Exception to
"""
out = str(exc)
if limit is None:
# TODO: config logging.exceptions.traceback_levels = 1
limit = int(os.environ.get('NICEMAN_EXC_STR_TBLIMIT', '1'))
try:
exctype, value, tb = sys.exc_info()
if not exc:
exc = value
out = str(exc)
# verify that it seems to be the exception we were passed
#assert(isinstance(exc, exctype))
if exc:
assert(exc is value)
entries = traceback.extract_tb(tb)
if entries:
out += " [%s]" % (','.join(['%s:%s:%d' % (os.path.basename(x[0]), x[2], x[1]) for x in entries[-limit:]]))
except:
return out # To the best of our abilities
finally:
# As the bible teaches us:
# https://docs.python.org/2/library/sys.html#sys.exc_info
del tb
return out