本文整理汇总了Python中tornado.ioloop.IOLoop.instance方法的典型用法代码示例。如果您正苦于以下问题:Python IOLoop.instance方法的具体用法?Python IOLoop.instance怎么用?Python IOLoop.instance使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tornado.ioloop.IOLoop
的用法示例。
在下文中一共展示了IOLoop.instance方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import instance [as 别名]
def run():
app = Application([("/", RootHandler)])
port = random.randrange(options.min_port, options.max_port)
app.listen(port, address='127.0.0.1')
signal.signal(signal.SIGCHLD, handle_sigchld)
args = ["ab"]
args.extend(["-n", str(options.n)])
args.extend(["-c", str(options.c)])
if options.keepalive:
args.append("-k")
if options.quiet:
# just stops the progress messages printed to stderr
args.append("-q")
args.append("http://127.0.0.1:%d/" % port)
subprocess.Popen(args)
IOLoop.instance().start()
IOLoop.instance().close()
del IOLoop._instance
assert not IOLoop.initialized()
示例2: tearDown
# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import instance [as 别名]
def tearDown(self):
# Clean up Subprocess, so it can be used again with a new ioloop.
Subprocess.uninitialize()
self.io_loop.clear_current()
if (not IOLoop.initialized() or
self.io_loop is not IOLoop.instance()):
# Try to clean up any file descriptors left open in the ioloop.
# This avoids leaks, especially when tests are run repeatedly
# in the same process with autoreload (because curl does not
# set FD_CLOEXEC on its file descriptors)
self.io_loop.close(all_fds=True)
super(AsyncTestCase, self).tearDown()
# In case an exception escaped or the StackContext caught an exception
# when there wasn't a wait() to re-raise it, do so here.
# This is our last chance to raise an exception in a way that the
# unittest machinery understands.
self.__rethrow()
示例3: run_tests
# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import instance [as 别名]
def run_tests():
url = options.url + '/getCaseCount'
control_ws = yield websocket_connect(url, None)
num_tests = int((yield control_ws.read_message()))
logging.info('running %d cases', num_tests)
msg = yield control_ws.read_message()
assert msg is None
for i in range(1, num_tests + 1):
logging.info('running test case %d', i)
url = options.url + '/runCase?case=%d&agent=%s' % (i, options.name)
test_ws = yield websocket_connect(url, None, compression_options={})
while True:
message = yield test_ws.read_message()
if message is None:
break
test_ws.write_message(message, binary=isinstance(message, bytes))
url = options.url + '/updateReports?agent=%s' % options.name
update_ws = yield websocket_connect(url, None)
msg = yield update_ws.read_message()
assert msg is None
IOLoop.instance().stop()
示例4: shutdown
# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import instance [as 别名]
def shutdown(self):
MAX_WAIT_SECONDS_BEFORE_SHUTDOWN = 3
print('Stopping http server')
self.http_server.stop()
print('Will shutdown in %s seconds ...' % MAX_WAIT_SECONDS_BEFORE_SHUTDOWN)
io_loop = IOLoop.instance()
deadline = time.time() + MAX_WAIT_SECONDS_BEFORE_SHUTDOWN
def stop_loop():
now = time.time()
if now < deadline and (io_loop._callbacks or io_loop._timeouts):
io_loop.add_timeout(now + 1, stop_loop)
else:
io_loop.stop()
print('Shutdown')
stop_loop()
示例5: listen
# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import instance [as 别名]
def listen(self, port, address="", **kwargs):
"""Starts an HTTP server for this application on the given port.
This is a convenience alias for creating an `.HTTPServer`
object and calling its listen method. Keyword arguments not
supported by `HTTPServer.listen <.TCPServer.listen>` are passed to the
`.HTTPServer` constructor. For advanced uses
(e.g. multi-process mode), do not use this method; create an
`.HTTPServer` and call its
`.TCPServer.bind`/`.TCPServer.start` methods directly.
Note that after calling this method you still need to call
``IOLoop.instance().start()`` to start the server.
"""
# import is here rather than top level because HTTPServer
# is not importable on appengine
from tornado.httpserver import HTTPServer
server = HTTPServer(self, **kwargs)
server.listen(port, address)
示例6: tornado_schedule
# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import instance [as 别名]
def tornado_schedule():
from tornado.ioloop import IOLoop
from apscheduler.schedulers.tornado import TornadoScheduler
def tick():
print('Tick! The time is: %s' % datetime.now())
scheduler = TornadoScheduler()
scheduler.add_job(tick, 'interval', seconds=3)
scheduler.start()
print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))
# Execution will block here until Ctrl+C (Ctrl+Break on Windows) is pressed.
try:
IOLoop.instance().start()
except (KeyboardInterrupt, SystemExit):
pass
示例7: main
# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import instance [as 别名]
def main():
parse_command_line()
app = Application([('/', ChunkHandler)])
app.listen(options.port, address='127.0.0.1')
def callback(response):
response.rethrow()
assert len(response.body) == (options.num_chunks * options.chunk_size)
logging.warning("fetch completed in %s seconds", response.request_time)
IOLoop.instance().stop()
logging.warning("Starting fetch with curl client")
curl_client = CurlAsyncHTTPClient()
curl_client.fetch('http://localhost:%d/' % options.port,
callback=callback)
IOLoop.instance().start()
logging.warning("Starting fetch with simple client")
simple_client = SimpleAsyncHTTPClient()
simple_client.fetch('http://localhost:%d/' % options.port,
callback=callback)
IOLoop.instance().start()
示例8: configure
# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import instance [as 别名]
def configure(impl, **kwargs):
"""Configures the AsyncHTTPClient subclass to use.
AsyncHTTPClient() actually creates an instance of a subclass.
This method may be called with either a class object or the
fully-qualified name of such a class (or None to use the default,
SimpleAsyncHTTPClient)
If additional keyword arguments are given, they will be passed
to the constructor of each subclass instance created. The
keyword argument max_clients determines the maximum number of
simultaneous fetch() operations that can execute in parallel
on each IOLoop. Additional arguments may be supported depending
on the implementation class in use.
Example::
AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient")
"""
if isinstance(impl, (unicode, bytes_type)):
impl = import_object(impl)
if impl is not None and not issubclass(impl, AsyncHTTPClient):
raise ValueError("Invalid AsyncHTTPClient implementation")
AsyncHTTPClient._impl_class = impl
AsyncHTTPClient._impl_kwargs = kwargs
示例9: add_accept_handler
# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import instance [as 别名]
def add_accept_handler(sock, callback, io_loop=None):
"""Adds an ``IOLoop`` event handler to accept new connections on ``sock``.
When a connection is accepted, ``callback(connection, address)`` will
be run (``connection`` is a socket object, and ``address`` is the
address of the other end of the connection). Note that this signature
is different from the ``callback(fd, events)`` signature used for
``IOLoop`` handlers.
"""
if io_loop is None:
io_loop = IOLoop.instance()
def accept_handler(fd, events):
while True:
try:
connection, address = sock.accept()
except socket.error, e:
if e.args[0] in (errno.EWOULDBLOCK, errno.EAGAIN):
return
raise
callback(connection, address)
示例10: __init__
# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import instance [as 别名]
def __init__(self, io_loop=None):
if not io_loop:
io_loop = tornado.ioloop.IOLoop.instance()
self._io_loop = io_loop
self._readers = {} # map of reader objects to fd
self._writers = {} # map of writer objects to fd
self._fds = {} # a map of fd to a (reader, writer) tuple
self._delayedCalls = {}
PosixReactorBase.__init__(self)
# IOLoop.start() bypasses some of the reactor initialization.
# Fire off the necessary events if they weren't already triggered
# by reactor.run().
def start_if_necessary():
if not self._started:
self.fireSystemEvent('startup')
self._io_loop.add_callback(start_if_necessary)
# IReactorTime
示例11: start
# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import instance [as 别名]
def start(self, init_callback):
def _():
try:
if asyncio is not None:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
self.serve_thrift()
self.serve_http()
ioloop = IOLoop.instance()
ioloop.add_callback(init_callback)
ioloop.start()
except Exception as e:
logging.error("server error: %s", e)
self.forsun.read_event.set()
timer.stop()
self.thread = threading.Thread(target=_)
self.thread.setDaemon(True)
self.thread.start()
示例12: handle_sigchld
# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import instance [as 别名]
def handle_sigchld(sig, frame):
IOLoop.instance().add_callback_from_signal(IOLoop.instance().stop)
示例13: start
# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import instance [as 别名]
def start(self):
old_current = IOLoop.current(instance=False)
try:
self._setup_logging()
self.make_current()
self.reactor.run()
finally:
if old_current is None:
IOLoop.clear_current()
else:
old_current.make_current()
示例14: get_new_ioloop
# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import instance [as 别名]
def get_new_ioloop(self):
"""Creates a new `.IOLoop` for this test. May be overridden in
subclasses for tests that require a specific `.IOLoop` (usually
the singleton `.IOLoop.instance()`).
"""
return IOLoop()
示例15: main
# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import instance [as 别名]
def main():
parse_command_line()
IOLoop.instance().add_callback(run_tests)
IOLoop.instance().start()