本文整理汇总了Python中tornado.ioloop.add_callback函数的典型用法代码示例。如果您正苦于以下问题:Python add_callback函数的具体用法?Python add_callback怎么用?Python add_callback使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了add_callback函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: stop
def stop(self):
"""
Stop tornado web server
"""
ioloop = tornado.ioloop.IOLoop.instance()
ioloop.add_callback(ioloop.stop)
logger.debug("Exiting tornado...")
示例2: fetch
def fetch(self, callback):
if len(self.logs) == 0:
self.callback = callback
else:
logs, self.logs = self.logs, []
for log in logs:
ioloop.add_callback(callback, log)
示例3: start_server
def start_server(args):
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.jinja_env.globals['static'] = static
blueprint.url_prefix = args.url_prefix
app.register_blueprint(blueprint)
# app.run(port=args.port, debug=args.debug)
wsgi_app = tornado.wsgi.WSGIContainer(app)
condajs_ws = sockjs.tornado.SockJSRouter(views.CondaJsWebSocketRouter, '/condajs_ws')
routes = condajs_ws.urls
routes.append((r".*", tornado.web.FallbackHandler, dict(fallback=wsgi_app)))
application = tornado.web.Application(routes, debug=args.debug)
try:
application.listen(args.port)
except OSError as e:
print("There was an error starting the server:")
print(e)
return
ioloop = tornado.ioloop.IOLoop.instance()
if not args.debug:
callback = lambda: webbrowser.open_new_tab('http://localhost:%s' % args.port)
ioloop.add_callback(callback)
ioloop.start()
示例4: main
def main():
options, args = get_args()
ioloop = tornado.ioloop.IOLoop.instance()
series = get_series_class(options)(options, ioloop)
application = Application(options, series, [
('/', IndexHandler),
('/update', UpdateHandler),
], static_path=STATIC_PATH)
try:
ip = get_ip_address('eth0')
except IOError:
ip = '127.0.0.1'
tornado.httpserver.HTTPServer(application).listen(options.port, ip)
url = 'http://%s:%s/' % (ip, options.port)
def announce():
print >>sys.stderr, "wplot running at: " + url
if options.browse:
ioloop.add_callback(lambda: webbrowser.open_new_tab(url))
ioloop.add_callback(announce)
try:
ioloop.start()
except (KeyboardInterrupt, IOError) as e:
pass
finally:
application._stop = True
示例5: enumerate_device
def enumerate_device(this_node, node_id, response):
global UAVCAN_NODE_INFO, UAVCAN_NODE_CONFIG
log.debug("enumerate_device({}, {!r})".format(node_id, response))
# Save the node info request and clear out the config
UAVCAN_NODE_INFO[node_id] = response
UAVCAN_NODE_CONFIG[node_id] = {}
# Send the node info message to all connected sockets
send_all(response.type.get_normalized_definition(), node_id, response)
# Schedule a parameter fetch if the node is in operating mode
if not response.status.mode:
ioloop.add_callback(enumerate_node_params, this_node, node_id)
# Check the supplied directory for updated firmware
if not firmware_dir:
log.debug("enumerate_device(): no firmware path specified")
return
# Search for firmware suitable for this device
device_name = response.name.decode()
available_files = firmware_files_for_device(
firmware_dir, device_name, response.hardware_version.major,
response.hardware_version.minor)
log.debug(("enumerate_device(): found {:d} firmware file(s) " +
"for device '{!s}'").format(
len(available_files), device_name))
for f in available_files:
log.debug(("enumerate_device(): {!s} " +
"(modified {:%Y-%m-%dT%H:%M:%S})").format(
f[-1], datetime.datetime.fromtimestamp(f[-2])))
# If there are files available, check the CRC of the latest version
# against the CRC of the firmware on the node.
if available_files:
firmware_path = available_files[0][-1]
with FirmwareImage(firmware_path, "rb") as f:
if f.app_descriptor.image_crc != \
response.software_version.image_crc:
# Version mismatch, send a BeginFirmwareUpdate with the
# appropriate path.
request = uavcan.protocol.file.BeginFirmwareUpdate(
mode="request")
request.source_node_id = this_node.node_id
request.image_file_remote_path.path.encode(
os.path.basename(firmware_path))
(response, response_transfer), _ = yield tornado.gen.Task(
this_node.send_request, request, node_id)
if response and response.error != response.ERROR_OK:
msg = ("[MASTER] #{0:03d} rejected "
"uavcan.protocol.file.BeginFirmwareUpdate " +
"with error {1:d}: {2!s}").format(
node_id, response.error,
response.optional_error_message.decode())
log.error(msg)
else:
log.debug("enumerate_device(): device up to date")
示例6: on_open
def on_open(self, info):
# type: (ConnectionInfo) -> None
log_data = dict(extra='[transport=%s]' % (self.session.transport_name,))
record_request_start_data(log_data)
ioloop = tornado.ioloop.IOLoop.instance()
self.authenticated = False
self.session.user_profile = None
self.close_info = None # type: CloseErrorInfo
self.did_close = False
try:
self.browser_session_id = info.get_cookie(settings.SESSION_COOKIE_NAME).value
self.csrf_token = info.get_cookie(settings.CSRF_COOKIE_NAME).value
except AttributeError:
# The request didn't contain the necessary cookie values. We can't
# close immediately because sockjs-tornado doesn't expect a close
# inside on_open(), so do it on the next tick.
self.close_info = CloseErrorInfo(403, "Initial cookie lacked required values")
ioloop.add_callback(self.close)
return
def auth_timeout():
# type: () -> None
self.close_info = CloseErrorInfo(408, "Timeout while waiting for authentication")
self.close()
self.timeout_handle = ioloop.add_timeout(time.time() + 10, auth_timeout)
write_log_line(log_data, path='/socket/open', method='SOCKET',
remote_ip=info.ip, email='unknown', client_name='?')
示例7: stop_server
def stop_server(server):
server.stop()
logger.info("Add stop callback.")
ioloop = tornado.ioloop.IOLoop.instance()
ioloop.add_callback(ioloop.stop)
logger.info("Maybe server stopping...")
os.system("taskkill /im python.exe")
示例8: open
def open(self):
ioloop = tornado.ioloop.IOLoop.instance()
ioloop.call_later(self._KEEPALIVE_PING_TIMEOUT, self._send_ping)
ioloop.add_callback(lambda: log.info('Client connected: {0}'.format(self)))
self._get_id()
self._CLIENTS[self.id] = self
self._log_client_list()
示例9: init_timers
def init_timers(self):
ioloop = tornado.ioloop.IOLoop.instance()
# The mongo status monitor. We set up one call immediately, and then
# try again every three seconds.
ioloop.add_callback(self.monitor_mongo_status)
res = tornado.ioloop.PeriodicCallback(self.monitor_mongo_status, 3000)
res.start()
示例10: on_close
def on_close(self):
ioloop = tornado.ioloop.IOLoop.instance()
if self._CLIENTS.has_key(self.id):
self._CLIENTS.pop(self.id)
for name, obj in iteritems(self.__handlers):
ioloop.add_callback(obj._onclose)
log.info('Client "{0}" disconnected'.format(self.id))
示例11: close
def close(self):
super(WebSocketBase, self).close()
ioloop = tornado.ioloop.IOLoop.instance()
for future in self.store.values():
ioloop.add_callback(partial(future.set_exception, ConnectionClosed))
ioloop.add_callback(lambda: self.on_close() if self.ws_connection else None)
示例12: read_callback
def read_callback(self, frame):
ts = frame.timestamp
ioloop.add_callback(lambda:self.publish(
'can.%03x' % frame.id, ts, frame.tojson()))
if self.obd2:
ioloop.add_callback(lambda:
self.obd2.read(ts, frame.tojson()))
示例13: gpio_loop
def gpio_loop():
ioloop = tornado.ioloop.IOLoop.current()
value = True
while True:
time.sleep(1.0)
value = not value
ioloop.add_callback(partial(WebSocketHandler.dispatch, value))
示例14: queue_response
def queue_response(self, response):
ioloop = tornado.ioloop.IOLoop.instance()
def send_response(*args):
self._send_response(response)
try:
# calling write_message or the socket is not thread safe
ioloop.add_callback(send_response)
except:
logging.error("Error adding callback", exc_info=True)
示例15: on_close
def on_close(self):
'''
Called when client closes this connection. Cleanup
is done here.
'''
if self.id in self.funcserver.websocks:
self.funcserver.websocks[self.id] = None
ioloop = tornado.ioloop.IOLoop.instance()
ioloop.add_callback(lambda: self.funcserver.websocks.pop(self.id, None))