本文整理汇总了Python中tornado.log.app_log.error函数的典型用法代码示例。如果您正苦于以下问题:Python error函数的具体用法?Python error怎么用?Python error使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了error函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: post
def post(self):
id = self.get_argument('id', '')
resource_url = self.get_argument('resource_url', '')
http_client = AsyncHTTPClient()
response = yield http_client.fetch("https://api.douban.com/v2/book/" + id)
response = json.loads(response.body)
book = None
try:
book = Book.objects(bid=id)[0]
except Exception as ex:
app_log.error(ex)
book = Book(bid=id,
title=response['title'],
image=response['images']['large'],
isbn13=response['isbn13'],
publisher=response['publisher'],
wcount=0,
dcount=0
)
finally:
book.save()
if resource_url:
self.share_network_file(book, resource_url)
else:
self.share_local_file(book, resource_url)
开发者ID:yunlzheng,项目名称:PDFLabs,代码行数:29,代码来源:find.py
示例2: _run_callback
def _run_callback(self, callback: Callable[[], Any]) -> None:
"""Runs a callback with error handling.
For use in subclasses.
"""
try:
ret = callback()
if ret is not None:
from tornado import gen
# Functions that return Futures typically swallow all
# exceptions and store them in the Future. If a Future
# makes it out to the IOLoop, ensure its exception (if any)
# gets logged too.
try:
ret = gen.convert_yielded(ret)
except gen.BadYieldError:
# It's not unusual for add_callback to be used with
# methods returning a non-None and non-yieldable
# result, which should just be ignored.
pass
else:
self.add_future(ret, self._discard_future_result)
except Exception:
app_log.error("Exception in callback %r", callback, exc_info=True)
开发者ID:rgbkrk,项目名称:tornado,代码行数:25,代码来源:ioloop.py
示例3: wrapper
def wrapper(*args, **kwargs):
try:
return callback(*args, **kwargs)
except Exception:
app_log.error("Uncaught exception in %s",
self.request.path, exc_info=True)
self._abort()
开发者ID:zhkzyth,项目名称:tornado-reading-notes,代码行数:7,代码来源:websocket.py
示例4: _api_request
def _api_request(self, method, url, **kwargs):
"""Make an API request"""
allow_404 = kwargs.pop('allow_404', False)
headers = kwargs.setdefault('headers', {})
headers.setdefault('Authorization', 'token %s' % self.api_token)
try:
r = requests.request(method, url, **kwargs)
except requests.ConnectionError as e:
app_log.error("Error connecting to %s: %s", self.api_url, e)
msg = "Failed to connect to Hub API at %r." % self.api_url
msg += " Is the Hub accessible at this URL (from host: %s)?" % socket.gethostname()
if '127.0.0.1' in self.api_url:
msg += " Make sure to set c.JupyterHub.hub_ip to an IP accessible to" + \
" single-user servers if the servers are not on the same host as the Hub."
raise HTTPError(500, msg)
data = None
if r.status_code == 404 and allow_404:
pass
elif r.status_code == 403:
app_log.error("I don't have permission to check authorization with JupyterHub, my auth token may have expired: [%i] %s", r.status_code, r.reason)
app_log.error(r.text)
raise HTTPError(500, "Permission failure checking authorization, I may need a new token")
elif r.status_code >= 500:
app_log.error("Upstream failure verifying auth token: [%i] %s", r.status_code, r.reason)
app_log.error(r.text)
raise HTTPError(502, "Failed to check authorization (upstream problem)")
elif r.status_code >= 400:
app_log.warning("Failed to check authorization: [%i] %s", r.status_code, r.reason)
app_log.warning(r.text)
raise HTTPError(500, "Failed to check authorization")
else:
data = r.json()
return data
开发者ID:angelapper,项目名称:jupyterhub,代码行数:35,代码来源:auth.py
示例5: __init__
def __init__(self, template_string, name="<string>", loader=None, compress_whitespace=None, autoescape=_UNSET):
self.name = name
if compress_whitespace is None:
compress_whitespace = name.endswith(".html") or name.endswith(".js")
if autoescape is not _UNSET:
self.autoescape = autoescape
elif loader:
self.autoescape = loader.autoescape
else:
self.autoescape = _DEFAULT_AUTOESCAPE
self.namespace = loader.namespace if loader else {}
reader = _TemplateReader(name, escape.native_str(template_string))
self.file = _File(self, _parse(reader, self))
self.code = self._generate_python(loader, compress_whitespace)
self.loader = loader
try:
# Under python2.5, the fake filename used here must match
# the module name used in __name__ below.
# The dont_inherit flag prevents template.py's future imports
# from being applied to the generated code.
self.compiled = compile(
escape.to_unicode(self.code), "%s.generated.py" % self.name.replace(".", "_"), "exec", dont_inherit=True
)
except Exception:
formatted_code = _format_code(self.code).rstrip()
app_log.error("%s code:\n%s", self.name, formatted_code)
raise
开发者ID:justzx2011,项目名称:tornado,代码行数:27,代码来源:template.py
示例6: get_client_secret
def get_client_secret(self, mpin_id):
"""Generate client secret."""
try:
return crypto.get_client_multiple(self.master_secret, mpin_id)
except crypto.CryptoError as e:
log.error(e)
raise SecretsError('Client secret generation failed')
开发者ID:CertiVox-i3-NTT,项目名称:milagro-mfa-server,代码行数:7,代码来源:secrets.py
示例7: finish_notebook
def finish_notebook(self, nbjson, download_url, home_url=None, msg=None, breadcrumbs=None):
"""render a notebook from its JSON body.
download_url is required, home_url is not.
msg is extra information for the log message when rendering fails.
"""
if msg is None:
msg = download_url
try:
app_log.debug("Requesting render of %s", download_url)
with self.time_block("Rendered %s" % download_url):
nbhtml, config = yield self.pool.submit(
render_notebook, self.exporter, nbjson, download_url,
config=self.config,
)
except NbFormatError as e:
app_log.error("Invalid notebook %s: %s", msg, e)
raise web.HTTPError(400, str(e))
except Exception as e:
app_log.error("Failed to render %s", msg, exc_info=True)
raise web.HTTPError(400, str(e))
else:
app_log.debug("Finished render of %s", download_url)
html = self.render_template('notebook.html',
body=nbhtml,
download_url=download_url,
home_url=home_url,
date=datetime.utcnow().strftime(date_fmt),
breadcrumbs=breadcrumbs,
**config)
yield self.cache_and_finish(html)
开发者ID:mariusvniekerk,项目名称:nbviewer,代码行数:33,代码来源:handlers.py
示例8: 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
示例9: get_places
def get_places(self, ll, q):
url = FacebookComm.BASE_URL.format(endpoint=FacebookComm.SEARCH_ENDPOINT)
place = None
try:
url += '&type=place¢er={ll}&distance=100&q={q}'.format(ll=ll, q=q)
log.info('Fetching Facebook places from [{0}]'.format(url))
request = HTTPRequest(url=url, connect_timeout=options.http_request_timeout, request_timeout=options.http_request_timeout)
response = yield self.client.fetch(request)
if response.code != 200:
raise FacebookError(response.code)
body = json.loads(response.body)
places = body['data']
if len(places) > 0:
place = places[0]
except HTTPError as e:
log.error('Facebook error [{0}] while calling [{1}]!'.format(e, url))
raise Return(None)
raise Return(place)
开发者ID:agentwx,项目名称:partyu-tornado-app,代码行数:25,代码来源:facebook.py
示例10: cache_and_finish
def cache_and_finish(self, content=""):
"""finish a request and cache the result
does not actually call finish - if used in @web.asynchronous,
finish must be called separately. But we never use @web.asynchronous,
because we are using gen.coroutine for async.
currently only works if:
- result is not written in multiple chunks
- custom headers are not used
"""
self.write(content)
short_url = self.truncate(self.request.path)
cache_data = pickle.dumps({"headers": self.cache_headers, "body": content}, pickle.HIGHEST_PROTOCOL)
request_time = self.request.request_time()
# set cache expiry to 120x request time
# bounded by cache_expiry_min,max
# a 30 second render will be cached for an hour
expiry = max(min(120 * request_time, self.cache_expiry_max), self.cache_expiry_min)
if self.request.uri in self.max_cache_uris:
# if it's a link from the front page, cache for a long time
expiry = self.cache_expiry_max
log = app_log.info if expiry > self.cache_expiry_min else app_log.debug
log("caching (expiry=%is) %s", expiry, short_url)
try:
with self.time_block("cache set %s" % short_url):
yield self.cache.set(self.cache_key, cache_data, int(time.time() + expiry))
except Exception:
app_log.error("cache set for %s failed", short_url, exc_info=True)
else:
app_log.debug("cache set finished %s", short_url)
开发者ID:B-Rich,项目名称:nbviewer,代码行数:34,代码来源:handlers.py
示例11: __init__
def __init__(self, *args, **kwargs):
super(HttpRequest, self).__init__(*args, **kwargs)
this.middleware_fac.set_request(self)
try:
this.middleware_fac.run_call(self)
except Exception, ex:
app_log.error(ex)
开发者ID:1060460048,项目名称:torngas,代码行数:7,代码来源:application.py
示例12: render_string
def render_string(self, filename, **kwargs):
'''
Override render_string to use mako template.
Like tornado render_string method, this method also
pass request handler environment to template engine
'''
try:
if not self.is_mobile():
template = self.LOOK_UP.get_template(filename)
else:
template = self.LOOK_UP_MOBILE.get_template(filename)
env_kwargs = dict(
handler = self,
request = self.request,
# current_user = self.current_user
locale = self.locale,
_ = self.locale.translate,
static_url = self.static_url,
xsrf_form_html = self.xsrf_form_html,
reverse_url = self.application.reverse_url,
)
env_kwargs.update(kwargs)
return template.render(**env_kwargs)
except:
from mako.exceptions import RichTraceback
tb = RichTraceback()
for (module_name, line_no, function_name, line) in tb.traceback:
print('File:{}, Line:{} in {}'.format(module_name, line_no, function_name))
print(line)
app_log.error('Render {} failed, {}:{}'.format(filename, tb.error.__class__.__name__, tb.error))
raise HTTPError(500, 'Render page failed')
开发者ID:hayate-hsu,项目名称:bidong_backend,代码行数:31,代码来源:ims.py
示例13: post
def post(self):
result = {'success': True}
dirname = '/var/todother/uploads/'
if self.request.files:
try:
upload_img = self.request.files['postfile'][0]
rawname = upload_img['filename']
destname = '%d%s' % (time.time(), ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(6)))
thumbname = 'thumb_%s' % destname
path = '%s/%s/pics/' % (dirname, self.current_user.user_id)
if not os.path.exists(path):
os.makedirs(path)
extension = os.path.splitext(rawname)[1]
destname = ''.join((path, destname, extension))
output_img = open(destname, 'w')
output_img.write(upload_img['body'])
output_img.close()
oimg = Image.open(destname)
oimg.thumbnail((160, 160), resample=1)
thumbname = ''.join((path, thumbname, extension))
oimg.save(thumbname)
result['thumbname'] = thumbname[len(dirname):]
result['filename'] = destname[len(dirname):]
except Exception, e:
app_log.error(str(e))
result['success'] = False
result['err_info'] = 'File type unsupported'
开发者ID:xiangcai,项目名称:todother,代码行数:28,代码来源:img.py
示例14: update_stats
def update_stats(stats):
"""Get updated stats for each host
If a host fails to reply,
assume it is is down and assign it zero availability and capacity
"""
http_client = AsyncHTTPClient()
futures = {}
for host in stats.keys():
app_log.debug("Checking stats on %s" % host)
req = HTTPRequest(host + '/stats')
futures[host] = http_client.fetch(req)
for host, f in futures.items():
try:
reply = yield f
data = json.loads(reply.body.decode('utf8'))
except Exception as e:
app_log.error("Failed to get stats for %s: %s", host, e)
if host in stats:
stats[host] = {'available': 0, 'capacity': 0, 'down': True}
else:
app_log.debug("Got stats from %s: %s", host, data)
if host in stats:
stats[host] = data
开发者ID:thewtex,项目名称:tmpnb-redirector,代码行数:26,代码来源:redirector.py
示例15: _generate_master_secret
def _generate_master_secret(self):
"""Generate the M-Pin Master Secret."""
try:
return crypto.mpin_random_generate(self.rng)
except crypto.CryptoError as e:
log.error(e)
raise SecretsError('M-Pin Master Secret Generation Failed')
开发者ID:CertiVox-i3-NTT,项目名称:milagro-mfa-server,代码行数:7,代码来源:secrets.py
示例16: post
def post(self, tag):
group = Group.objects(tag=tag)[0]
title = self.get_argument('title')
content = self.get_argument('content')
now = datetime.datetime.now()
mode = self.get_argument('type').decode()
if mode == 'new':
try:
if not title:
raise Exception('title is none')
post = Post(group=group,
author=self.get_curent_user_model(),
title=title,
content=content,
create_at=now,
update_at=now
)
post.save()
return self.redirect("/group/" + tag + "/" + str(post.id))
except Exception as ex:
app_log.error(ex)
return self.redirect("/group/" + tag)
elif mode == 'update':
id = self.get_argument('id')
try:
app_log.debug(id)
app_log.debug(title)
app_log.debug(content)
post = Post.objects(id=id)[0]
post.title = title
post.content = content
post.save()
except Exception as ex:
app_log.error(ex)
return self.redirect("/group/" + tag + "/" + id)
开发者ID:yunlzheng,项目名称:PDFLabs,代码行数:35,代码来源:group_handler.py
示例17: get_server_secret
def get_server_secret(self):
"""Generate server secret."""
try:
return crypto.get_server_secret(self.master_secret)
except crypto.CryptoError as e:
log.error(e)
raise SecretsError('Server Secret generation failed')
开发者ID:CertiVox-i3-NTT,项目名称:milagro-mfa-server,代码行数:7,代码来源:secrets.py
示例18: _handle_connection
def _handle_connection(self, connection, address):
if self.ssl_options is not None:
assert ssl, "Python 2.6+ and OpenSSL required for SSL"
try:
connection = ssl_wrap_socket(connection,
self.ssl_options,
server_side=True,
do_handshake_on_connect=False)
except ssl.SSLError as err:
if err.args[0] == ssl.SSL_ERROR_EOF:
return connection.close()
else:
raise
except socket.error as err:
if err.args[0] == errno.ECONNABORTED:
return connection.close()
else:
raise
try:
if self.ssl_options is not None:
stream = SSLIOStream(connection, io_loop=self.io_loop)
else:
stream = IOStream(connection, io_loop=self.io_loop)
self.handle_stream(stream, address)
except Exception:
app_log.error("Error in connection callback", exc_info=True)
开发者ID:wojons,项目名称:tornadoMulti,代码行数:26,代码来源:tcpserver.py
示例19: _get_certivox_server_secret_share_dta
def _get_certivox_server_secret_share_dta(self, expires):
path = 'serverSecret'
url_params = url_concat('{0}{1}'.format(Keys.certivoxServer(), path), {
'app_id': self.app_id,
'expires': expires,
'signature': signMessage('{0}{1}{2}'.format(path, self.app_id, expires), self.app_key)
})
log.debug('MIRACL server secret request: {0}'.format(url_params))
httpclient = tornado.httpclient.HTTPClient()
try:
response = httpclient.fetch(url_params, **fetchConfig(url_params))
except tornado.httpclient.HTTPError as e:
log.error(e)
raise SecretsError('Unable to get Server Secret from the MIRACL TA server')
httpclient.close()
try:
data = json.loads(response.body)
except ValueError as e:
log.error(e)
raise SecretsError('Invalid response from TA server')
if 'serverSecret' not in data:
raise SecretsError('serverSecret not in response from TA server')
return data["serverSecret"]
开发者ID:CertiVox-i3-NTT,项目名称:milagro-mfa-server,代码行数:26,代码来源:secrets.py
示例20: _log_rate_limit
def _log_rate_limit(self, future):
"""log GitHub rate limit headers
- error if 0 remaining
- warn if 10% or less remain
- debug otherwise
"""
try:
r = future.result()
except HTTPError as e:
r = e.response
limit_s = r.headers.get("X-RateLimit-Limit", "")
remaining_s = r.headers.get("X-RateLimit-Remaining", "")
if not remaining_s or not limit_s:
if r.code < 300:
app_log.warn("No rate limit headers. Did GitHub change? %s", json.dumps(r.headers, indent=1))
return
remaining = int(remaining_s)
limit = int(limit_s)
if remaining == 0:
jsondata = response_text(r)
data = json.loads(jsondata)
app_log.error("GitHub rate limit (%s) exceeded: %s", limit, data.get("message", "no message"))
return
if 10 * remaining > limit:
log = app_log.debug
else:
log = app_log.warn
log("%i/%i GitHub API requests remaining", remaining, limit)
开发者ID:f3r,项目名称:nbviewer,代码行数:31,代码来源:client.py
注:本文中的tornado.log.app_log.error函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论