本文整理汇总了Python中tornado.log.app_log.info函数的典型用法代码示例。如果您正苦于以下问题:Python info函数的具体用法?Python info怎么用?Python info使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了info函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: show
def show(handlers, url_width, handler_width):
app_log.info("=" * int(url_width + handler_width))
app_log.info("%-*s%-*s" % (url_width, "URL", handler_width, "HANDLER"))
app_log.info("=" * int(url_width + handler_width))
for url, _ in handlers:
app_log.info("%-*s%-*s" % (url_width, url, handler_width, _))
app_log.info("=" * int(url_width + handler_width))
示例2: get
def get(self, path=None):
'''Spawns a brand new server'''
try:
if path is None:
# No path. Assign a prelaunched container from the pool and redirect to it.
# Append self.redirect_uri to the redirect target.
container_path = self.pool.acquire().path
app_log.info("Allocated [%s] from the pool.", container_path)
url = "/{}/{}".format(container_path, self.redirect_uri)
else:
path_parts = path.lstrip('/').split('/', 1)
container_path = path_parts[0]
# Scrap a container from the pool and replace it with an ad-hoc replacement.
# This takes longer, but is necessary to support ad-hoc containers
yield self.pool.adhoc(container_path)
app_log.info("Allocated ad-hoc container at [%s].", container_path)
url = path
app_log.debug("Redirecting [%s] -> [%s].", self.request.path, url)
self.redirect(url, permanent=False)
except spawnpool.EmptyPoolError:
app_log.warning("The container pool is empty!")
self.render("full.html", cull_period=self.cull_period)
示例3: get
def get(self):
error = self.get_argument("error", False)
if error:
msg = self.get_argument("error_description", error)
raise HTTPError(400, "Error in oauth: %s" % msg)
code = self.get_argument("code", False)
if not code:
raise HTTPError(400, "oauth callback made without a token")
# validate OAuth state
arg_state = self.get_argument("state", None)
if arg_state is None:
raise HTTPError("oauth state is missing. Try logging in again.")
cookie_name = self.hub_auth.get_state_cookie_name(arg_state)
cookie_state = self.get_secure_cookie(cookie_name)
# clear cookie state now that we've consumed it
self.clear_cookie(cookie_name, path=self.hub_auth.base_url)
if isinstance(cookie_state, bytes):
cookie_state = cookie_state.decode('ascii', 'replace')
# check that state matches
if arg_state != cookie_state:
app_log.warning("oauth state %r != %r", arg_state, cookie_state)
raise HTTPError(403, "oauth state does not match. Try logging in again.")
next_url = self.hub_auth.get_next_url(cookie_state)
# TODO: make async (in a Thread?)
token = self.hub_auth.token_for_code(code)
session_id = self.hub_auth.get_session_id(self)
user_model = self.hub_auth.user_for_token(token, session_id=session_id)
if user_model is None:
raise HTTPError(500, "oauth callback failed to identify a user")
app_log.info("Logged-in user %s", user_model)
self.hub_auth.set_cookie(self, token)
self.redirect(next_url or self.hub_auth.base_url)
示例4: cull_idle
def cull_idle(url, api_token, timeout):
"""cull idle single-user servers"""
auth_header = {
'Authorization': 'token %s' % api_token
}
req = HTTPRequest(url=url + '/api/users',
headers=auth_header,
)
now = datetime.datetime.utcnow()
cull_limit = now - datetime.timedelta(seconds=timeout)
client = AsyncHTTPClient()
resp = yield client.fetch(req)
users = json.loads(resp.body.decode('utf8', 'replace'))
futures = []
for user in users:
last_activity = parse_date(user['last_activity'])
if user['server'] and last_activity < cull_limit:
app_log.info("Culling %s (inactive since %s)", user['name'], last_activity)
req = HTTPRequest(url=url + '/api/users/%s/server' % user['name'],
method='DELETE',
headers=auth_header,
)
futures.append((user['name'], client.fetch(req)))
elif user['server'] and last_activity > cull_limit:
app_log.debug("Not culling %s (active since %s)", user['name'], last_activity)
for (name, f) in futures:
yield f
app_log.debug("Finished culling %s", name)
示例5: get
def get(self):
code = self.get_argument("code", False)
if not code:
raise HTTPError(400, "oauth callback made without a token")
# validate OAuth state
arg_state = self.get_argument("state", None)
cookie_state = self.get_secure_cookie(self.hub_auth.state_cookie_name)
next_url = None
if arg_state or cookie_state:
# clear cookie state now that we've consumed it
self.clear_cookie(self.hub_auth.state_cookie_name)
if isinstance(cookie_state, bytes):
cookie_state = cookie_state.decode('ascii', 'replace')
# check that state matches
if arg_state != cookie_state:
app_log.debug("oauth state %r != %r", arg_state, cookie_state)
raise HTTPError(403, "oauth state does not match")
next_url = self.hub_auth.get_next_url(cookie_state)
# TODO: make async (in a Thread?)
token = self.hub_auth.token_for_code(code)
user_model = self.hub_auth.user_for_token(token)
if user_model is None:
raise HTTPError(500, "oauth callback failed to identify a user")
app_log.info("Logged-in user %s", user_model)
self.hub_auth.set_cookie(self, token)
self.redirect(next_url or self.hub_auth.base_url)
示例6: main
def main():
options.define('port', default=9005,
help="Port for the REST API"
)
options.define('ip', default='127.0.0.1',
help="IP address for the REST API"
)
options.define('host_mount', default='',
help='Path where the host root is mounted in this container'
)
options.define('pool_prefix', default='',
help='Prefix assigned by tmpnb to its pooled containers'
)
options.define('registration_key', default='',
help='Registration key required to create new volumes'
)
options.parse_command_line()
opts = options.options
# regex from docker volume create
api_handlers = [
(r'/api/mounts(/([a-zA-Z0-9][a-zA-Z0-9_.-])+)?', MountsHandler),
(r'/api/volumes', VolumesHander),
]
api_app = web.Application(api_handlers)
api_app.listen(opts.port, opts.ip, xheaders=True)
app_log.info("Listening on {}:{}".format(opts.ip, opts.port))
ioloop.IOLoop.instance().start()
示例7: get
def get(self, user, repo, ref, path):
raw_url = u"https://raw.github.com/{user}/{repo}/{ref}/{path}".format(
user=user, repo=repo, ref=ref, path=quote(path)
)
blob_url = u"https://github.com/{user}/{repo}/blob/{ref}/{path}".format(
user=user, repo=repo, ref=ref, path=quote(path),
)
with self.catch_client_error():
response = yield self.client.fetch(raw_url)
if response.effective_url.startswith("https://github.com/{user}/{repo}/tree".format(
user=user, repo=repo
)):
tree_url = "/github/{user}/{repo}/tree/{ref}/{path}/".format(
user=user, repo=repo, ref=ref, path=quote(path),
)
app_log.info("%s is a directory, redirecting to %s", raw_url, tree_url)
self.redirect(tree_url)
return
filedata = response.body
if path.endswith('.ipynb'):
try:
nbjson = response_text(response)
except Exception as e:
app_log.error("Failed to decode notebook: %s", raw_url, exc_info=True)
raise web.HTTPError(400)
yield self.finish_notebook(nbjson, raw_url,
home_url=blob_url,
msg="file from GitHub: %s" % raw_url,
)
else:
self.set_header("Content-Type", "text/plain")
self.cache_and_finish(filedata)
示例8: _start_control
def _start_control(self):
app_log.info("Starting EE Control on port {port}".format(port=config.Control.Rest.PORT))
self._control_process = _start_remote_rest_server(config.Control.Rest.BIN, config.Control.Rest.PORT,
config.Control.Rest.DEBUG)
if self._control_process.is_running() and self._rest_server_listening(config.Control.Rest.BASE_URI):
app_log.info("EEControl REST Server running")
else:
app_log.error("EEControl REST Server not running")
exit(1)
if self._is_engine_supported(
_get_full_uri(config.Control.Rest.BASE_URI, config.Control.Rest.Endpoints.ENGINES)):
app_log.info("{engine} supported by EE Control".format(engine=config.Engine.NAME))
else:
app_log.error("{engine} is not supported by EE Control".format(engine=config.Engine.NAME))
exit(1)
if self._set_engine(_get_full_uri(config.Control.Rest.BASE_URI, config.Control.Rest.Endpoints.ENGINES)):
app_log.info("{engine} set by EE Control".format(engine=config.Engine.NAME))
else:
app_log.error("{engine} not set by EE Control".format(engine=config.Engine.NAME))
exit(1)
if self._connect_control():
app_log.info("EE Control client connected to engine")
else:
app_log.error("EE Control client couldn't connect to engine")
exit(1)
示例9: get
def get(self, file_name, *args, **kwargs):
if not file_name:
return self.send_error(status_code=404)
root_dir = os.path.dirname(os.path.dirname(__file__))
file_path = os.path.join(root_dir, "../static/download/" + file_name)
buf_size = 4096
self.set_header("Content-Type", "application/octet-stream")
self.set_header("Content-Disposition", "attachment; filename=" + file_name)
try:
download_file = open(file_path, "r")
while True:
data = download_file.read(buf_size)
if not data:
break
self.write(data)
download_file.close()
app_log.info("[{ip}] download file success: {name}".format(
ip=self.request.remote_ip, name=file_path
))
except IOError:
app_log.info("[{ip}] download file fail: {name}".format(
ip=self.request.remote_ip, name=file_path
))
return self.send_error(status_code=404)
self.finish()
示例10: start
def start(self):
# reset all connections
try:
app_log.info("Starting Connection Manager!")
if self.idl is not None:
self.idl.close()
# set up the schema and register all tables
self.schema_helper = SchemaHelper(self.schema)
self.schema_helper.register_all()
self.idl = Idl(self.remote, self.schema_helper)
self.curr_seqno = self.idl.change_seqno
# we do not reset transactions when the DB connection goes down
if self.transactions is None:
self.transactions = OvsdbTransactionList()
self.idl_run()
self.monitor_connection()
except Exception as e:
# TODO: log this exception
# attempt again in the next IOLoop iteration
app_log.info("Connection Manager failed! Reason: %s" % e)
IOLoop.current().add_timeout(time.time() + self.timeout,
self.start)
示例11: prepare
def prepare(self):
request = self.request
if request.headers and 'Content-Encoding' in request.headers:
del request.headers['Content-Encoding']
request.body_arguments = {}
request.files = {}
tornado.httputil.parse_body_arguments(
request.headers.get("Content-Type", ""), request.body, request.body_arguments, request.files)
for k, v in request.body_arguments.items():
request.arguments.setdefault(k, []).extend(v)
# cookie
cookieId = self.get_cookie('cookie_id')
if not cookieId or not Session.getSession(cookieId):
# create cookie id
ua = self.request.headers.get("User-Agent", '')
ip = self.request.remote_ip
time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
md5 = hashlib.md5()
md5.update((ua + ip + time).encode())
cookieId = md5.hexdigest()
Session.createSession(cookieId)
app_log.info('set cookie id ' + cookieId)
self.set_cookie('cookie_id', cookieId, path="/", expires_days=30)
self.cookieId = cookieId
self.db = self.settings['db']
示例12: render_notebook
def render_notebook(exporter, json_as_string, url=None, forced_theme=None):
app_log.info("rendering %d B notebook from %s", len(json_as_string), url)
try:
share_as_object = json.loads(json_as_string)
except ValueError:
raise SyntaxError("Notebook does not appear to be JSON: %r" % json_as_string[:16])
template = None
if share_as_object.get('notebookModel') and share_as_object.get('cellModel'):
template = 'old/beaker_section.html'
elif share_as_object.get('notebookModel'):
template = 'old/beaker_notebook.html'
elif share_as_object.get('cellModel'):
template = 'old/beaker_cell.html'
elif share_as_object.get('beaker'):
template = 'beaker_notebook.html'
name = 'Beaker Notebook'
config = {
'download_name': name,
'css_theme': None,
'template': template
}
return json_as_string, config
示例13: test_put_user
def test_put_user(self):
client = yield self.auth_client()
user = yield self.create_user(client)
cases = [
("login", "foofoofoo"),
("email", "[email protected]"),
("is_admin", False),
("disabled", False),
("password", str(uuid.uuid4()))
]
for i in range(1, len(cases)):
for case in itertools.combinations(cases, i):
body = dict(case)
if 'disabled' in body:
log.info("Deleting user: %r", user['id'])
yield client.fetch(
self.get_url("/api/v1/user/{0}".format(user['id'])),
"DELETE"
)
log.info("Send body: %r", body)
response = yield client.fetch(
self.get_url("/api/v1/user/{0}".format(user['id'])),
"PUT", body
)
for k, v in body.items():
if k == 'password':
continue
self.assertIn(k, response.body)
self.assertEqual(v, response.body[k])
示例14: test_put_errors
def test_put_errors(self):
client = yield self.auth_client()
user = yield self.create_user(client)
cases = [
("login", False),
("login", [2, 3]),
("email", "@bbb.com"),
("email", {1: 2}),
("password", "123"),
("password", "1"),
("password", [1, '2']),
("password", {1: '2'}),
]
for i in range(1, len(cases)):
for case in itertools.combinations(cases, i):
body = dict(case)
with self.assertRaises(HTTPError) as err:
log.info("Body: %s", body)
yield client.fetch(
self.get_url("/api/v1/user/{0}".format(user['id'])),
"PUT", body
)
self.assertEqual(err.exception.code, 400)
示例15: render_notebook
def render_notebook(exporter, nbfile, nb, url=None, config=None):
if not isinstance(exporter, Exporter):
exporter_cls = exporter
if exporter_cls not in exporters:
app_log.info("instantiating %s" % exporter_cls.__name__)
exporters[exporter_cls] = exporter_cls(config=config, log=app_log)
exporter = exporters[exporter_cls]
css_theme = nb.get('metadata', {}).get('_nbviewer', {}).get('css', None)
if not css_theme or not css_theme.strip():
# whitespace
css_theme = None
# get the notebook title, if any
try:
name = nb.metadata.name
except AttributeError:
name = ''
if not name and url is not None:
name = url.rsplit('/')[-1]
if not name.endswith(".ipynb"):
name = name + ".ipynb"
html, resources = exporter.from_filename(nbfile)
config = {
'download_name': name,
'css_theme': css_theme,
}
return html, config