本文整理汇总了Python中tornado.log.gen_log.error函数的典型用法代码示例。如果您正苦于以下问题:Python error函数的具体用法?Python error怎么用?Python error使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了error函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: make_static_url
def make_static_url(cls, settings, path):
"""Constructs a versioned url for the given path.
This method may be overridden in subclasses (but note that it is
a class method rather than an instance method).
``settings`` is the `Application.settings` dictionary. ``path``
is the static path being requested. The url returned should be
relative to the current host.
"""
abs_path = os.path.join(settings["static_path"], path)
with cls._lock:
hashes = cls._static_hashes
if abs_path not in hashes:
try:
f = open(abs_path, "rb")
hashes[abs_path] = hashlib.md5(f.read()).hexdigest()
f.close()
except Exception:
gen_log.error("Could not open static file %r", path)
hashes[abs_path] = None
hsh = hashes.get(abs_path)
static_url_prefix = settings.get("static_url_prefix", "/static/")
if hsh:
return static_url_prefix + path + "?v=" + hsh[:5]
else:
return static_url_prefix + path
开发者ID:pombredanne,项目名称:winterpy,代码行数:27,代码来源:httpserver.py
示例2: _handle_request_exception
def _handle_request_exception(self, e):
if not isinstance(e, Interruption):
return tornado.web.RequestHandler._handle_request_exception(self, e)
# copy of tornado.web.RequestHandler._handle_request_exception
# but remove exception report
if isinstance(e, tornado.web.Finish):
# Not an error; just finish the request without logging.
if not self._finished:
self.finish()
return
# this is not an error
# do not report exception
# self.log_exception(*sys.exc_info())
if self._finished:
# Extra errors after the request has been finished should
# be logged, but there is no reason to continue to try and
# send a response.
return
if isinstance(e, tornado.web.HTTPError):
if e.status_code not in tornado.httputil.responses and not e.reason:
gen_log.error("Bad HTTP status code: %d", e.status_code)
else:
self.send_error(e.status_code, exc_info=sys.exc_info())
return
self.send_error(500, exc_info=sys.exc_info())
开发者ID:SakuraSa,项目名称:TenhouLoggerX,代码行数:28,代码来源:Page.py
示例3: main
def main():
config.init(persistent_path)
tornado.options.parse_config_file(conf_path, final=False)
tornado.options.parse_command_line()
key = config.get_option('cookie_secret')
if key is None:
gen_log.error('Fatal: secret key not found. '
'Run `manage.py keys` to create it')
sys.exit()
settings['cookie_secret'] = key
auth.init()
application = tornado.web.Application(
routes,
**settings
)
server = tornado.httpserver.HTTPServer(application)
server.listen(options.server_port)
tornado.ioloop.IOLoop.instance().start()
开发者ID:wkevina,项目名称:garage,代码行数:25,代码来源:server.py
示例4: _callback
def _callback(fut):
exc = fut.exc_info()
if exc:
if not isinstance(exc[1], etcdexcept.EtcdException):
# We can't get the list of machines, if one server is in the
# machines cache, try on it
_log.error("Failed to get list of machines from %s%s: %r and retry it.",
uri, self.version_prefix, exc)
if self._machines_cache:
self._base_url = self._machines_cache.pop(0)
_log.debug("Retrying on %s", self._base_url)
# Call myself
self.ioloop.add_future(self.search_machine(), _callback)
return
else:
raise etcdexcept.EtcdException("Could not get the list of servers, "
"maybe you provided the wrong "
"host(s) to connect to?")
else:
response = fut.result()
machines = [
node.strip() for node in
self._handle_server_response(response).body.decode('utf-8').split(',')
]
_log.debug("Retrieved list of machines: %s", machines)
self._machines_cache = machines
if self._base_url not in self._machines_cache:
self._base_url = self._choice_machine()
callback(fut.result())
开发者ID:zsc1528,项目名称:tornetcd,代码行数:29,代码来源:client.py
示例5: _server_request_loop
async def _server_request_loop(
self, delegate: httputil.HTTPServerConnectionDelegate
) -> None:
try:
while True:
conn = HTTP1Connection(self.stream, False, self.params, self.context)
request_delegate = delegate.start_request(self, conn)
try:
ret = await conn.read_response(request_delegate)
except (
iostream.StreamClosedError,
iostream.UnsatisfiableReadError,
asyncio.CancelledError,
):
return
except _QuietException:
# This exception was already logged.
conn.close()
return
except Exception:
gen_log.error("Uncaught exception", exc_info=True)
conn.close()
return
if not ret:
return
await asyncio.sleep(0)
finally:
delegate.on_close(self)
开发者ID:bdarnell,项目名称:tornado,代码行数:28,代码来源:http1connection.py
示例6: set_blocking_signal_threshold
def set_blocking_signal_threshold(self, seconds, action):
if not hasattr(signal, "setitimer"):
gen_log.error("set_blocking_signal_threshold requires a signal module " "with the setitimer method")
return
self._blocking_signal_threshold = seconds
if seconds is not None:
signal.signal(signal.SIGALRM, action if action is not None else signal.SIG_DFL)
开发者ID:GodZZila,项目名称:SickRage,代码行数:7,代码来源:ioloop.py
示例7: _server_request_loop
def _server_request_loop(self, delegate):
try:
while True:
conn = HTTP1Connection(self.stream, False,
self.params, self.context)
request_delegate = delegate.start_request(self, conn)
try:
ret = yield conn.read_response(request_delegate)
except (iostream.StreamClosedError,
iostream.UnsatisfiableReadError):
return
except _QuietException:
# This exception was already logged.
conn.close()
return
except Exception as e:
if 1 != e.errno:
gen_log.error("Uncaught exception", exc_info=True)
conn.close()
return
if not ret:
return
yield gen.moment
finally:
delegate.on_close(self)
开发者ID:JackDandy,项目名称:SickGear,代码行数:25,代码来源:http1connection.py
示例8: _run
def _run(self):
if not self._running: return
self._running = False
try:
self.callback()
except Exception:
gen_log.error("Error in delayed callback", exc_info=True)
开发者ID:326029212,项目名称:pyzmq,代码行数:7,代码来源:ioloop.py
示例9: send_error
def send_error(self, status_code=500, **kwargs):
"""Sends the given HTTP error code to the browser.
If `flush()` has already been called, it is not possible to send
an error, so this method will simply terminate the response.
If output has been written but not yet flushed, it will be discarded
and replaced with the error page.
Override `write_error()` to customize the error page that is returned.
Additional keyword arguments are passed through to `write_error`.
"""
if self._headers_written:
gen_log.error("Cannot send error response after headers written")
if not self._finished:
self.finish()
return
# Need keep headers
#self.clear()
reason = kwargs.get('reason')
if 'exc_info' in kwargs:
exception = kwargs['exc_info'][1]
if isinstance(exception, HTTPError) and exception.reason:
reason = exception.reason
self.set_status(status_code, reason=reason)
try:
self.write_error(status_code, **kwargs)
except Exception:
app_log.error("Uncaught exception in write_error", exc_info=True)
if not self._finished:
self.finish()
开发者ID:Yuanye,项目名称:takeaway,代码行数:29,代码来源:base.py
示例10: load_gettext_translations
def load_gettext_translations(directory, domain):
"""Loads translations from gettext's locale tree
Locale tree is similar to system's /usr/share/locale, like:
{directory}/{lang}/LC_MESSAGES/{domain}.mo
Three steps are required to have you app translated:
1. Generate POT translation file
xgettext --language=Python --keyword=_:1,2 -d cyclone file1.py file2.html etc
2. Merge against existing POT file:
msgmerge old.po cyclone.po > new.po
3. Compile:
msgfmt cyclone.po -o {directory}/pt_BR/LC_MESSAGES/cyclone.mo
"""
import gettext
global _translations
global _supported_locales
global _use_gettext
_translations = {}
for lang in os.listdir(directory):
if lang.startswith('.'):
continue # skip .svn, etc
if os.path.isfile(os.path.join(directory, lang)):
continue
try:
os.stat(os.path.join(directory, lang, "LC_MESSAGES", domain + ".mo"))
_translations[lang] = gettext.translation(domain, directory,
languages=[lang])
except Exception, e:
gen_log.error("Cannot load translation for '%s': %s", lang, str(e))
continue
开发者ID:Aliced3645,项目名称:tornado,代码行数:35,代码来源:locale.py
示例11: _execute
def _execute(self, cursor, query, parameters):
try:
return cursor.execute(query, parameters)
except OperationalError:
gen_log.error("Error connecting to MySQL on %s", self.host)
self.close()
raise
开发者ID:dvdotsenko,项目名称:tornado,代码行数:7,代码来源:database.py
示例12: __init__
def __init__(self, host, database, user=None, password=None,
max_idle_time=7 * 3600):
self.host = host
self.database = database
self.max_idle_time = max_idle_time
args = dict(conv=CONVERSIONS, use_unicode=True, charset="utf8",
db=database, init_command='SET time_zone = "+0:00"',
sql_mode="TRADITIONAL")
if user is not None:
args["user"] = user
if password is not None:
args["passwd"] = password
# We accept a path to a MySQL socket file or a host(:port) string
if "/" in host:
args["unix_socket"] = host
else:
self.socket = None
pair = host.split(":")
if len(pair) == 2:
args["host"] = pair[0]
args["port"] = int(pair[1])
else:
args["host"] = host
args["port"] = 3306
self._db = None
self._db_args = args
self._last_use_time = time.time()
try:
self.reconnect()
except Exception:
gen_log.error("Cannot connect to MySQL on %s", self.host,
exc_info=True)
开发者ID:dvdotsenko,项目名称:tornado,代码行数:35,代码来源:database.py
示例13: get
def get(self, uid, tid):
ota = yield self.db_temp.get_ota(tid)
if ota is None:
gen_log.error("Not ota field")
self.set_status(400)
self.finish({"error", "Can't found ota status."})
self.finish(jsonify(ota))
开发者ID:awong1900,项目名称:temp-io,代码行数:7,代码来源:temp.py
示例14: _handle_events
def _handle_events(self, fd, events):
"""This method is the actual handler for IOLoop, that gets called whenever
an event on my socket is posted. It dispatches to _handle_recv, etc."""
# print "handling events"
if not self.socket:
gen_log.warning("Got events for closed stream %s", fd)
return
try:
# dispatch events:
if events & IOLoop.ERROR:
gen_log.error("got POLLERR event on ZMQStream, which doesn't make sense")
return
if events & IOLoop.READ:
self._handle_recv()
if not self.socket:
return
if events & IOLoop.WRITE:
self._handle_send()
if not self.socket:
return
# rebuild the poll state
self._rebuild_io_state()
except:
gen_log.error("Uncaught exception, closing connection.",
exc_info=True)
self.close()
raise
开发者ID:FlavioFalcao,项目名称:pyzmq,代码行数:28,代码来源:zmqstream.py
示例15: _read_to_buffer
def _read_to_buffer(self):
"""Reads from the socket and appends the result to the read buffer.
Returns the number of bytes read. Returns 0 if there is nothing
to read (i.e. the read returns EWOULDBLOCK or equivalent). On
error closes the socket and raises an exception.
"""
try:
chunk = self.read_from_fd()
except (socket.error, IOError, OSError) as e:
# ssl.SSLError is a subclass of socket.error
if e.args[0] == errno.ECONNRESET:
# Treat ECONNRESET as a connection close rather than
# an error to minimize log spam (the exception will
# be available on self.error for apps that care).
self.close(exc_info=True)
return
self.close(exc_info=True)
raise
if chunk is None:
return 0
self._read_buffer.append(chunk)
self._read_buffer_size += len(chunk)
if self._read_buffer_size >= self.max_buffer_size:
gen_log.error("Reached maximum read buffer size")
self.close()
raise IOError("Reached maximum read buffer size")
return len(chunk)
开发者ID:08opt,项目名称:tornado,代码行数:28,代码来源:iostream.py
示例16: get_user
def get_user(self, token):
if not token:
raise gen.Return((None, "Requires authentication"))
user = None
result = yield self.db_user.get_user_by_token(token)
if result is None:
try:
data = yield sso.auth_token(token)
print data['ext'].get('picture')
doc_user = {
'id': data['user_id'],
'sign_in_provider': data['ext']['firebase']['sign_in_provider'],
'email': '' or data['ext'].get('email'),
'picture': '' or data['ext'].get('picture'),
'tokens': [
{
'token': data['token'],
'expire': datetime.utcfromtimestamp(int(data['expire']))
}
]}
yield self.db_user.add_user(data['user_id'], doc_user)
user = {'id': data['user_id']}
except Exception as e:
gen_log.error(e)
raise gen.Return((None, "SSO authenticate token failure, {}".format(str(e))))
else:
result = yield self.db_user.is_expire(token)
if result is None:
raise gen.Return((None, "Authentication has expired"))
user = {'id': result['id'], 'token': token}
raise gen.Return((user, ''))
开发者ID:awong1900,项目名称:temp-io,代码行数:33,代码来源:base.py
示例17: _load_version
def _load_version(abs_path):
try:
hsh = cls.get_content_version(abs_path)
mtm = cls.get_content_modified_time(abs_path)
return mtm, hsh
except Exception:
gen_log.error("Could not open static file %r", abs_path)
return None, None
开发者ID:lepture,项目名称:python-livereload,代码行数:9,代码来源:handlers.py
示例18: _get_func
def _get_func(self, request, m, func):
try:
cls = []
if hasattr(request, m):
cls = getattr(request, m)
if len(cls):
cls = cls.pop()
return getattr(cls, func)
except Exception, ex:
gen_log.error(ex)
开发者ID:EddieZhao,项目名称:torngas,代码行数:11,代码来源:manager.py
示例19: api
def api(self, path, **kwargs):
try:
import time
s_time = time.time()
data = yield self._make_request(path, **kwargs)
e_time = time.time()
gen_log.info("=====Time request wio api, {}".format(float(e_time)-float(s_time)))
except Exception as e:
gen_log.error(e)
raise
raise gen.Return(data)
开发者ID:awong1900,项目名称:temp-io,代码行数:11,代码来源:wioapi.py
示例20: cpu_count
def cpu_count():
"""Returns the number of processors on this machine."""
try:
return multiprocessing.cpu_count()
except NotImplementedError:
pass
try:
return os.sysconf("SC_NPROCESSORS_CONF")
except ValueError:
pass
gen_log.error("Could not detect number of processors; assuming 1")
return 1
开发者ID:1stvamp,项目名称:tornado,代码行数:12,代码来源:process.py
注:本文中的tornado.log.gen_log.error函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论