Python tornado.ioloop.IOLoop.instance() Examples

The following are 30 code examples of tornado.ioloop.IOLoop.instance(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tornado.ioloop.IOLoop , or try the search function .
Example #1
Source File: benchmark.py    From tornado-zh with MIT License 6 votes vote down vote up
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() 
Example #2
Source File: web.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
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) 
Example #3
Source File: server.py    From forsun with MIT License 6 votes vote down vote up
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() 
Example #4
Source File: twisted.py    From honeything with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #5
Source File: web.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
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) 
Example #6
Source File: netutil.py    From honeything with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #7
Source File: httpclient.py    From honeything with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #8
Source File: chunk_benchmark.py    From honeything with GNU General Public License v3.0 6 votes vote down vote up
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() 
Example #9
Source File: api.py    From watchdog with Apache License 2.0 6 votes vote down vote up
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() 
Example #10
Source File: benchmark.py    From honeything with GNU General Public License v3.0 6 votes vote down vote up
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() 
Example #11
Source File: testing.py    From tornado-zh with MIT License 6 votes vote down vote up
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() 
Example #12
Source File: client.py    From tornado-zh with MIT License 6 votes vote down vote up
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() 
Example #13
Source File: schdule.py    From Python-notes with MIT License 6 votes vote down vote up
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 
Example #14
Source File: testing.py    From tornado-zh with MIT License 6 votes vote down vote up
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() 
Example #15
Source File: BaseHandlers.py    From SpoofcheckSelfTest with Apache License 2.0 5 votes vote down vote up
def initialize(self):
        ''' Setup sessions, etc '''
        self.config = ConfigManager.instance() 
Example #16
Source File: benchmark.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
def handle_sigchld(sig, frame):
    IOLoop.instance().add_callback(IOLoop.instance().stop) 
Example #17
Source File: websocket.py    From vmaas with GNU General Public License v2.0 5 votes vote down vote up
def main():
    """Main entrypoint."""
    init_logging()
    create_app()
    IOLoop.instance().start() 
Example #18
Source File: websocket.py    From vmaas with GNU General Public License v2.0 5 votes vote down vote up
def stop():
        """Stop the websocket"""
        IOLoop.instance().stop() 
Example #19
Source File: websocket.py    From vmaas with GNU General Public License v2.0 5 votes vote down vote up
def create_app():
    """Create websocket tornado app."""
    app = WebsocketApplication()

    def terminate(*_):
        """Trigger shutdown."""
        IOLoop.instance().add_callback_from_signal(app.stop)

    signals = (signal.SIGHUP, signal.SIGTERM, signal.SIGINT)
    for sig in signals:
        signal.signal(sig, terminate)

    app.listen(8082) 
Example #20
Source File: BaseHandlers.py    From SpoofcheckSelfTest with Apache License 2.0 5 votes vote down vote up
def initialize(self):
        ''' Setup sessions, etc '''
        self.config = ConfigManager.instance() 
Example #21
Source File: test_tornado_PEP492.py    From gremlinclient with MIT License 5 votes vote down vote up
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() 
Example #22
Source File: test_tornado_PEP492.py    From gremlinclient with MIT License 5 votes vote down vote up
def tearDown(self):
        # Clean up Subprocess, so it can be used again with a new ioloop.
        Subprocess.uninitialize()
        self.loop.clear_current()
        if (not IOLoop.initialized() or
                self.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.loop.close(all_fds=True)
        super(TornadoFactoryConnectTest, self).tearDown() 
Example #23
Source File: test_ioloop.py    From pySINDy with MIT License 5 votes vote down vote up
def xtest_instance(self):
            """Green IOLoop.instance returns the right object"""
            loop = self.IOLoop.instance()
            if not t5asyncio:
                assert isinstance(loop, self.IOLoop)
            base_loop = BaseIOLoop.instance()
            assert base_loop is loop 
Example #24
Source File: tornado_wsgi.py    From web_develop with GNU General Public License v3.0 5 votes vote down vote up
def main():
    define('port', default=9000, type=int, help='Port on which to listen.')
    parse_command_line()

    http_server = HTTPServer(WSGIContainer(app))
    http_server.listen(options.port)
    IOLoop.instance().start() 
Example #25
Source File: origami.py    From origami-lib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run(self):
        """
        Starts the flask server over Tornados WSGI Container interface
        Also provide websocket interface at /websocket for persistent
        connections

        To run this server just create an instance of Origami Class and call
        this function

        .. code-block:: python

            from origami_lib.origami import Origami

            app = Origami("My Model")
            app.run()


        Raises:
            OrigamiServerException: Exception when the port we are trying to \
                bind to is already in use.
        """
        try:
            port = constants.DEFAULT_PORT
            http_server = WSGIContainer(self.server)

            # Register a web application with websocket at /websocket
            server = Application([(r'/websocket', OrigamiWebSocketHandler),
                                  (r'/fass', FunctionServiceHandler),
                                  (r'.*', FallbackHandler,
                                   dict(fallback=http_server))])

            server.listen(port)
            print("Origami server running on port: {}".format(port))
            IOLoop.instance().start()
        except OSError:
            raise exceptions.OrigamiServerException(
                "ORIGAMI SERVER ERROR: Port {0} already in use.".format(port)) 
Example #26
Source File: testing.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        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() 
Example #27
Source File: twisted.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
def install(io_loop=None):
    """Install this package as the default Twisted reactor."""
    if not io_loop:
        io_loop = tornado.ioloop.IOLoop.instance()
    reactor = TornadoReactor(io_loop)
    from twisted.internet.main import installReactor
    installReactor(reactor)
    return reactor 
Example #28
Source File: twisted.py    From pySINDy with MIT License 5 votes vote down vote up
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() 
Example #29
Source File: httpclient.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
def __new__(cls, io_loop=None, max_clients=None, force_instance=False,
                **kwargs):
        io_loop = io_loop or IOLoop.instance()
        if cls is AsyncHTTPClient:
            if cls._impl_class is None:
                from tornado.simple_httpclient import SimpleAsyncHTTPClient
                AsyncHTTPClient._impl_class = SimpleAsyncHTTPClient
            impl = AsyncHTTPClient._impl_class
        else:
            impl = cls
        if io_loop in impl._async_clients() and not force_instance:
            return impl._async_clients()[io_loop]
        else:
            instance = super(AsyncHTTPClient, cls).__new__(impl)
            args = {}
            if cls._impl_kwargs:
                args.update(cls._impl_kwargs)
            args.update(kwargs)
            if max_clients is not None:
                # max_clients is special because it may be passed
                # positionally instead of by keyword
                args["max_clients"] = max_clients
            elif "max_clients" not in args:
                args["max_clients"] = AsyncHTTPClient._DEFAULT_MAX_CLIENTS
            instance.initialize(io_loop, **args)
            if not force_instance:
                impl._async_clients()[io_loop] = instance
            return instance 
Example #30
Source File: test_tornado.py    From thrift_connector with MIT License 5 votes vote down vote up
def get_new_ioloop(self):
        return IOLoop.instance()