本文整理汇总了Python中tornado.ioloop.IOLoop类的典型用法代码示例。如果您正苦于以下问题:Python IOLoop类的具体用法?Python IOLoop怎么用?Python IOLoop使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了IOLoop类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_errors_dont_block
def test_errors_dont_block():
c = Center('127.0.0.1', 8017)
w = Worker('127.0.0.2', 8018, c.ip, c.port, ncores=1)
e = Executor((c.ip, c.port), start=False)
@gen.coroutine
def f():
c.listen(c.port)
yield w._start()
IOLoop.current().spawn_callback(e._go)
L = [e.submit(inc, 1),
e.submit(throws, 1),
e.submit(inc, 2),
e.submit(throws, 2)]
i = 0
while not (L[0].status == L[2].status == 'finished'):
i += 1
if i == 1000:
assert False
yield gen.sleep(0.01)
result = yield e._gather([L[0], L[2]])
assert result == [2, 3]
yield w._close()
c.stop()
IOLoop.current().run_sync(f)
示例2: respond
def respond(self, result=None, error=None, batch_results=None, allow_async=True):
'''Respond to the request with the given result or error object (the ``batch_results`` and
``allow_async`` parameters are for internal use only and not intended to be supplied manually).
Responses will be serialized according to the ``response_type`` propery. The default
serialization is "application/json". Other supported protocols are:
* application/bson - requires pymongo
* application/msgpack - requires msgpack-python
The response will also contain any available session information.
To help with error handling in asynchronous methods, calling ``handler.respond(error=<your_error>)`` with a caught
exception will trigger a normal Toto error response, log the error and finish the request. This is the same basic
flow that is used internally when exceptions are raised from synchronous method calls.
The "error" property of the response is derived from the ``error`` parameter in the following ways:
1. If ``error`` is an instance of ``TotoException``, "error" will be a dictionary with "value" and "code" keys matching those of the ``TotoException``.
2. In all other cases, ``error`` is first converted to a ``TotoException`` with ``code = <ERROR_SERVER>`` and ``value = str(error)`` before following (1.).
To send custom error information, pass an instance of ``TotoException`` with ``value = <some_json_serializable_object>``.
'''
#if the handler is processing an async method, schedule the response on the main runloop
if self.async and allow_async:
IOLoop.instance().add_callback(lambda: self.respond(result, error, batch_results, False))
return
示例3: send_request
def send_request(self, request):
"""Send the given request and response is required.
Use this for messages which have a response message.
:param request:
request to send
:returns:
A Future containing the response for the request
"""
assert self._loop_running, "Perform a handshake first."
assert request.id not in self._outstanding, (
"Message ID '%d' already being used" % request.id
)
future = tornado.gen.Future()
self._outstanding[request.id] = future
self.stream_request(request)
if request.ttl:
self._add_timeout(request, future)
# the actual future that caller will yield
response_future = tornado.gen.Future()
# TODO: fire before_receive_response
IOLoop.current().add_future(
future,
lambda f: self.adapt_result(f, request, response_future),
)
return response_future
示例4: test_send_email_single_blacklisted_domain
def test_send_email_single_blacklisted_domain(smtp_sendmail, options):
options = add_options(options)
func = partial(accounts.utils.send_email, '[email protected]', 'test subject', 'test message')
IOLoop.instance().run_sync(func)
assert not smtp_sendmail.called
示例5: on_pong
def on_pong(self, data):
"""Clear the timeout, sleep, and send a new ping.
.. todo::
* Document the times used in this method.
The calculations are in my black notebook
XD.
"""
try:
if self.ping_timeout_handle is not None:
IOLoop.current().remove_timeout(
self.ping_timeout_handle)
yield sleep(conf.ping_sleep)
self.ping(b'1')
self.ping_timeout_handle = \
IOLoop.current().call_later(
conf.ping_timeout, self.close)
except WebSocketClosedError:
pass
except:
raise
示例6: run
def run(self):
# Global as I can't work out a way to get it into PrinterStateConnection
global printer
global gcodeManager
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.web import Application, FallbackHandler
# first initialize the settings singleton and make sure it uses given configfile and basedir if available
self._initSettings(self._configfile, self._basedir)
# then initialize logging
self._initLogging(self._debug)
gcodeManager = gcodefiles.GcodeManager()
printer = Printer(gcodeManager)
if self._host is None:
self._host = settings().get(["server", "host"])
if self._port is None:
self._port = settings().getInt(["server", "port"])
logging.getLogger(__name__).info("Listening on http://%s:%d" % (self._host, self._port))
app.debug = self._debug
self._router = tornadio2.TornadioRouter(PrinterStateConnection)
self._tornado_app = Application(self._router.urls + [
(".*", FallbackHandler, {"fallback": WSGIContainer(app)})
])
self._server = HTTPServer(self._tornado_app)
self._server.listen(self._port, address=self._host)
IOLoop.instance().start()
示例7: tearDown
def tearDown(self):
self.http_server.stop()
self.io_loop.run_sync(self.http_server.close_all_connections)
if (not IOLoop.initialized() or
self.http_client.io_loop is not IOLoop.instance()):
self.http_client.close()
super(AsyncHTTPTestCase, self).tearDown()
示例8: _on_finish
def _on_finish():
try:
zs_response = self.zsle_request(data['sim'])
zlp = ZsLeParser(zs_response.replace('GBK', 'UTF-8'))
if zlp.success == "0":
ret.success = ErrorCode.SUCCESS
ret.position = zlp.get_position()
ret.info = ErrorCode.ERROR_MESSAGE[ret.success]
logging.info("[LE] Zsle response position: %s, sim:%s", ret.position, data['sim'])
else:
if zlp.success == "9999228":
callback = partial(self.re_subscription, data['sim'])
IOLoop.instance().add_timeout(int(time.time()) + 5, callback)
logging.info("[LE] Zsle request failed, errorcode: %s, info: %s, sim:%s",
zlp.success, zlp.info, data['sim'])
# logging.info('[LE] Google request:\n %s', request)
# response = self.send(ConfHelper.LBMP_CONF.le_host,
# ConfHelper.LBMP_CONF.le_url,
# request,
# HTTP.METHOD.POST)
# logging.info('[LE] Google response:\n %s', response.decode('utf8'))
# json_data = json_decode(response)
# if json_data.get("location"):
# ret.position.lat = int(json_data["location"]["latitude"] * 3600000)
# ret.position.lon = int(json_data["location"]["longitude"] * 3600000)
# ret.success = ErrorCode.SUCCESS
# ret.info = ErrorCode.ERROR_MESSAGE[ret.success]
except Exception as e:
logging.exception("[LE] Get latlon failed. Exception: %s, sim:%s", e.args, data['sim'])
self.write(ret)
IOLoop.instance().add_callback(self.finish)
示例9: main
def main():
define('listen', metavar='IP', default='127.0.0.1', help='listen on IP address (default 127.0.0.1)')
define('port', metavar='PORT', default=8888, type=int, help='listen on PORT (default 8888)')
define('debug', metavar='True|False', default=False, type=bool,
help='enable Tornado debug mode: templates will not be cached '
'and the app will watch for changes to its source files '
'and reload itself when anything changes')
options.parse_command_line()
settings = dict(
template_path=rel('templates'),
static_path=rel('static'),
debug=options.debug
)
application = Application([
(r'/', MainHandler),
(r'/ws', EchoWebSocket),
(r'/websocket', SignallingHandler),
(r'/webrtc', WebRTCHandler)
], **settings)
#application.listen(address=options.listen, port=options.port)
application.listen(7080)
IOLoop.instance().start()
示例10: main
def main():
'''Create server, begin IOLoop
'''
tornado.options.parse_command_line()
http_server = HTTPServer(Application(), xheaders=True)
http_server.listen(options.port)
IOLoop.instance().start()
示例11: test_stepdown_triggers_refresh
def test_stepdown_triggers_refresh(self, done):
c_find_one = motor.MotorReplicaSetClient(
self.seed, replicaSet=self.name).open_sync()
# We've started the primary and one secondary
primary = ha_tools.get_primary()
secondary = ha_tools.get_secondaries()[0]
self.assertEqual(
one(c_find_one.secondaries), _partition_node(secondary))
ha_tools.stepdown_primary()
# Make sure the stepdown completes
yield gen.Task(IOLoop.instance().add_timeout, time.time() + 1)
# Trigger a refresh
yield AssertRaises(AutoReconnect, c_find_one.test.test.find_one)
# Wait for the immediate refresh to complete - we're not waiting for
# the periodic refresh, which has been disabled
yield gen.Task(IOLoop.instance().add_timeout, time.time() + 1)
# We've detected the stepdown
self.assertTrue(
not c_find_one.primary
or primary != _partition_node(c_find_one.primary))
done()
示例12: main
def main():
global http_server
try:
signal(SIGTERM, on_signal)
parse_command_line()
if options.config != None:
parse_config_file(options.config)
path = join(dirname(__file__), "templates")
application = Application(
[(r"/", IndexHandler), (r"/stock", StockHandler)],
template_path=path,
static_path=join(dirname(__file__), "static"),
)
application.db = motor.MotorClient(options.db_host, options.db_port).open_sync()[options.db_name]
http_server = HTTPServer(application)
http_server.listen(options.port, options.address)
log().info("server listening on port %s:%d" % (options.address, options.port))
if log().isEnabledFor(DEBUG):
log().debug("autoreload enabled")
tornado.autoreload.start()
IOLoop.instance().start()
except KeyboardInterrupt:
log().info("exiting...")
except BaseException as ex:
log().error("exiting due: [%s][%s]" % (str(ex), str(format_exc().splitlines())))
exit(1)
示例13: test_set_not_none_trace_equal_trace_id
def test_set_not_none_trace_equal_trace_id(self):
new_trace = Trace(300, 20, 10)
IOLoop.current().run_sync(partial(self.tx.dummy, trace=new_trace))
# Keep old trace_id, keep old logger
assert self.tx.trace_id is not new_trace.traceid
assert self.tx.log is self.initial_log
示例14: test_set_not_none_trace
def test_set_not_none_trace(self):
new_trace_id = 100
new_trace = Trace(new_trace_id, 2, 1)
IOLoop.current().run_sync(partial(self.tx.dummy, trace=new_trace))
# Set new trace_id, set new logger adapter
assert self.tx.trace_id == new_trace_id
assert self.tx.log.extra == {'trace_id': '{:016x}'.format(new_trace_id)}
示例15: save
def save(self, data):
if data != '':
self.fd.write(data)
else:
self.fd.close()
print "File is saved to " + self.store_path
IOLoop.instance().stop()