Python tornado.ioloop.IOLoop() Examples

The following are 30 code examples of tornado.ioloop.IOLoop(). 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 , or try the search function .
Example #1
Source File: testing.py    From pySINDy with MIT License 6 votes vote down vote up
def stop(self, _arg=None, **kwargs):
        """Stops the `.IOLoop`, causing one pending (or future) call to `wait()`
        to return.

        Keyword arguments or a single positional argument passed to `stop()` are
        saved and will be returned by `wait()`.

        .. deprecated:: 5.1

           `stop` and `wait` are deprecated; use ``@gen_test`` instead.
        """
        assert _arg is None or not kwargs
        self.__stop_args = kwargs or _arg
        if self.__running:
            self.io_loop.stop()
            self.__running = False
        self.__stopped = True 
Example #2
Source File: testing.py    From opendevops with GNU General Public License v3.0 6 votes vote down vote up
def stop(self, _arg: Any = None, **kwargs: Any) -> None:
        """Stops the `.IOLoop`, causing one pending (or future) call to `wait()`
        to return.

        Keyword arguments or a single positional argument passed to `stop()` are
        saved and will be returned by `wait()`.

        .. deprecated:: 5.1

           `stop` and `wait` are deprecated; use ``@gen_test`` instead.
        """
        assert _arg is None or not kwargs
        self.__stop_args = kwargs or _arg
        if self.__running:
            self.io_loop.stop()
            self.__running = False
        self.__stopped = True 
Example #3
Source File: testing.py    From teleport with Apache License 2.0 6 votes vote down vote up
def stop(self, _arg: Any = None, **kwargs: Any) -> None:
        """Stops the `.IOLoop`, causing one pending (or future) call to `wait()`
        to return.

        Keyword arguments or a single positional argument passed to `stop()` are
        saved and will be returned by `wait()`.

        .. deprecated:: 5.1

           `stop` and `wait` are deprecated; use ``@gen_test`` instead.
        """
        assert _arg is None or not kwargs
        self.__stop_args = kwargs or _arg
        if self.__running:
            self.io_loop.stop()
            self.__running = False
        self.__stopped = True 
Example #4
Source File: snap.py    From pypot with GNU General Public License v3.0 6 votes vote down vote up
def run(self, quiet=None, server=''):
        """ Start the tornado server, run forever.
            'quiet' and 'server' arguments are no longer used, they are keep only for backward compatibility
        """

        try:
            loop = IOLoop()
            http_server = HTTPServer(WSGIContainer(self.app))
            http_server.listen(self.port)
            loop.start()

        except socket.error as serr:
            # Re raise the socket error if not "[Errno 98] Address already in use"
            if serr.errno != errno.EADDRINUSE:
                raise serr
            else:
                logger.warning("""The webserver port {} is already used.
The SnapRobotServer is maybe already run or another software use this port.""".format(self.port)) 
Example #5
Source File: BokehServer.py    From BAC0 with GNU Lesser General Public License v3.0 6 votes vote down vote up
def startServer(self):
        self.server = Server(
            {
                "/devices": self._dev_app_ref(),
                "/trends": self._trends_app_ref(),
                "/notes": self._notes_app_ref(),
            },
            io_loop=IOLoop(),
            allow_websocket_origin=[
                "{}:8111".format(self.IP),
                "{}:5006".format(self.IP),
                "{}:8111".format("localhost"),
                "{}:5006".format("localhost"),
            ],
        )
        self.server.start()
        self.server.io_loop.start() 
Example #6
Source File: autoreload.py    From opendevops with GNU General Public License v3.0 6 votes vote down vote up
def start(check_time: int = 500) -> None:
    """Begins watching source files for changes.

    .. versionchanged:: 5.0
       The ``io_loop`` argument (deprecated since version 4.1) has been removed.
    """
    io_loop = ioloop.IOLoop.current()
    if io_loop in _io_loops:
        return
    _io_loops[io_loop] = True
    if len(_io_loops) > 1:
        gen_log.warning("tornado.autoreload started more than once in the same process")
    modify_times = {}  # type: Dict[str, float]
    callback = functools.partial(_reload_on_update, modify_times)
    scheduler = ioloop.PeriodicCallback(callback, check_time)
    scheduler.start() 
Example #7
Source File: autoreload.py    From tornado-zh with MIT License 6 votes vote down vote up
def start(io_loop=None, check_time=500):
    """Begins watching source files for changes.

    .. versionchanged:: 4.1
       The ``io_loop`` argument is deprecated.
    """
    io_loop = io_loop or ioloop.IOLoop.current()
    if io_loop in _io_loops:
        return
    _io_loops[io_loop] = True
    if len(_io_loops) > 1:
        gen_log.warning("tornado.autoreload started more than once in the same process")
    if _has_execv:
        add_reload_hook(functools.partial(io_loop.close, all_fds=True))
    modify_times = {}
    callback = functools.partial(_reload_on_update, modify_times)
    scheduler = ioloop.PeriodicCallback(callback, check_time, io_loop=io_loop)
    scheduler.start() 
Example #8
Source File: test_server.py    From panel with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_server_static_dirs():
    html = Markdown('# Title')

    loop = IOLoop()
    server = StoppableThread(
        target=html._get_server, io_loop=loop,
        args=(5008, None, None, loop, False, True, None, False, None),
        kwargs=dict(static_dirs={'tests': os.path.dirname(__file__)}))
    server.start()

    # Wait for server to start
    time.sleep(1)

    r = requests.get("http://localhost:5008/tests/test_server.py")
    with open(__file__) as f:
        assert f.read() == r.content.decode('utf-8')
    server.stop() 
Example #9
Source File: autoreload.py    From tornado-zh with MIT License 6 votes vote down vote up
def start(io_loop=None, check_time=500):
    """Begins watching source files for changes.

    .. versionchanged:: 4.1
       The ``io_loop`` argument is deprecated.
    """
    io_loop = io_loop or ioloop.IOLoop.current()
    if io_loop in _io_loops:
        return
    _io_loops[io_loop] = True
    if len(_io_loops) > 1:
        gen_log.warning("tornado.autoreload started more than once in the same process")
    if _has_execv:
        add_reload_hook(functools.partial(io_loop.close, all_fds=True))
    modify_times = {}
    callback = functools.partial(_reload_on_update, modify_times)
    scheduler = ioloop.PeriodicCallback(callback, check_time, io_loop=io_loop)
    scheduler.start() 
Example #10
Source File: test_fixtures.py    From pytest-tornado with Apache License 2.0 6 votes vote down vote up
def test_type_annotation(testdir):

    testdir.makepyfile(
        test_type_annotation="""
            import pytest
            from tornado.ioloop import IOLoop

            @pytest.mark.gen_test
            def test_type_attrib(io_loop: IOLoop):
                pass  # Only check that gen_test works
        """,
    )

    # Run tests
    result = testdir.runpytest_inprocess()

    # Check tests went off as they should:
    assert result.ret == 0 
Example #11
Source File: autoreload.py    From zulip with Apache License 2.0 6 votes vote down vote up
def start(io_loop=None, check_time=500):
    """Begins watching source files for changes.

    .. versionchanged:: 4.1
       The ``io_loop`` argument is deprecated.
    """
    io_loop = io_loop or ioloop.IOLoop.current()
    if io_loop in _io_loops:
        return
    _io_loops[io_loop] = True
    if len(_io_loops) > 1:
        gen_log.warning("tornado.autoreload started more than once in the same process")
    modify_times = {}
    callback = functools.partial(_reload_on_update, modify_times)
    scheduler = ioloop.PeriodicCallback(callback, check_time, io_loop=io_loop)
    scheduler.start() 
Example #12
Source File: test_repoproviders.py    From binderhub with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_gitlab_ref():
    namespace = 'gitlab-org/gitlab-foss'
    spec = '{}/{}'.format(
        quote(namespace, safe=''),
        quote('v10.0.6')
    )
    provider = GitLabRepoProvider(spec=spec)
    slug = provider.get_build_slug()
    assert slug == 'gitlab_-org-gitlab_-foss'
    full_url = provider.get_repo_url()
    assert full_url == f'https://gitlab.com/{namespace}.git'
    ref = IOLoop().run_sync(provider.get_resolved_ref)
    assert ref == 'b3344b7f17c335a817c5d7608c5e47fd7cabc023'
    ref_url = IOLoop().run_sync(provider.get_resolved_ref_url)
    assert ref_url == f'https://gitlab.com/{namespace}/tree/{ref}'
    resolved_spec = IOLoop().run_sync(provider.get_resolved_spec)
    assert resolved_spec == quote(namespace, safe='') + f'/{ref}' 
Example #13
Source File: httpclient_test.py    From opendevops with GNU General Public License v3.0 6 votes vote down vote up
def tearDown(self):
        def stop_server():
            self.server.stop()
            # Delay the shutdown of the IOLoop by several iterations because
            # the server may still have some cleanup work left when
            # the client finishes with the response (this is noticeable
            # with http/2, which leaves a Future with an unexamined
            # StreamClosedError on the loop).

            @gen.coroutine
            def slow_stop():
                yield self.server.close_all_connections()
                # The number of iterations is difficult to predict. Typically,
                # one is sufficient, although sometimes it needs more.
                for i in range(5):
                    yield
                self.server_ioloop.stop()

            self.server_ioloop.add_callback(slow_stop)

        self.server_ioloop.add_callback(stop_server)
        self.server_thread.join()
        self.http_client.close()
        self.server_ioloop.close(all_fds=True) 
Example #14
Source File: autoreload.py    From teleport with Apache License 2.0 6 votes vote down vote up
def start(check_time=500):
    """Begins watching source files for changes.

    .. versionchanged:: 5.0
       The ``io_loop`` argument (deprecated since version 4.1) has been removed.
    """
    io_loop = ioloop.IOLoop.current()
    if io_loop in _io_loops:
        return
    _io_loops[io_loop] = True
    if len(_io_loops) > 1:
        gen_log.warning("tornado.autoreload started more than once in the same process")
    modify_times = {}
    callback = functools.partial(_reload_on_update, modify_times)
    scheduler = ioloop.PeriodicCallback(callback, check_time)
    scheduler.start() 
Example #15
Source File: testing.py    From teleport with Apache License 2.0 6 votes vote down vote up
def stop(self, _arg=None, **kwargs):
        """Stops the `.IOLoop`, causing one pending (or future) call to `wait()`
        to return.

        Keyword arguments or a single positional argument passed to `stop()` are
        saved and will be returned by `wait()`.

        .. deprecated:: 5.1

           `stop` and `wait` are deprecated; use ``@gen_test`` instead.
        """
        assert _arg is None or not kwargs
        self.__stop_args = kwargs or _arg
        if self.__running:
            self.io_loop.stop()
            self.__running = False
        self.__stopped = True 
Example #16
Source File: twisted_test.py    From honeything with GNU General Public License v3.0 6 votes vote down vote up
def _testReadWrite(self):
        """
        In this test the writer writes an 'x' to its fd. The reader
        reads it, check the value and ends the test.
        """
        self.shouldWrite = True

        def checkReadInput(fd):
            self.assertEquals(fd.read(), 'x')
            self._reactor.stop()

        def writeOnce(fd):
            if self.shouldWrite:
                self.shouldWrite = False
                fd.write('x')
        self._reader = Reader(self._p1, checkReadInput)
        self._writer = Writer(self._p2, writeOnce)

        self._reactor.addWriter(self._writer)

        # Test that adding the reader twice adds it only once to
        # IOLoop.
        self._reactor.addReader(self._reader)
        self._reactor.addReader(self._reader) 
Example #17
Source File: test_auth.py    From pySINDy with MIT License 6 votes vote down vote up
def with_ioloop(method, expect_success=True):
    """decorator for running tests with an IOLoop"""
    def test_method(self):
        r = method(self)

        loop = self.io_loop
        if expect_success:
            self.pullstream.on_recv(self.on_message_succeed)
        else:
            self.pullstream.on_recv(self.on_message_fail)
        
        loop.call_later(1, self.attempt_connection)
        loop.call_later(1.2, self.send_msg)
        
        if expect_success:
            loop.call_later(2, self.on_test_timeout_fail)
        else:
            loop.call_later(2, self.on_test_timeout_succeed)
        
        loop.start()
        if self.fail_msg:
            self.fail(self.fail_msg)
        
        return r
    return test_method 
Example #18
Source File: testing.py    From teleport with Apache License 2.0 6 votes vote down vote up
def stop(self, _arg: Any = None, **kwargs: Any) -> None:
        """Stops the `.IOLoop`, causing one pending (or future) call to `wait()`
        to return.

        Keyword arguments or a single positional argument passed to `stop()` are
        saved and will be returned by `wait()`.

        .. deprecated:: 5.1

           `stop` and `wait` are deprecated; use ``@gen_test`` instead.
        """
        assert _arg is None or not kwargs
        self.__stop_args = kwargs or _arg
        if self.__running:
            self.io_loop.stop()
            self.__running = False
        self.__stopped = True 
Example #19
Source File: test_auth.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def with_ioloop(method, expect_success=True):
    """decorator for running tests with an IOLoop"""
    def test_method(self):
        r = method(self)

        loop = self.io_loop
        if expect_success:
            self.pullstream.on_recv(self.on_message_succeed)
        else:
            self.pullstream.on_recv(self.on_message_fail)
        
        loop.call_later(1, self.attempt_connection)
        loop.call_later(1.2, self.send_msg)
        
        if expect_success:
            loop.call_later(2, self.on_test_timeout_fail)
        else:
            loop.call_later(2, self.on_test_timeout_succeed)
        
        loop.start()
        if self.fail_msg:
            self.fail(self.fail_msg)
        
        return r
    return test_method 
Example #20
Source File: autoreload.py    From teleport with Apache License 2.0 6 votes vote down vote up
def start(check_time: int = 500) -> None:
    """Begins watching source files for changes.

    .. versionchanged:: 5.0
       The ``io_loop`` argument (deprecated since version 4.1) has been removed.
    """
    io_loop = ioloop.IOLoop.current()
    if io_loop in _io_loops:
        return
    _io_loops[io_loop] = True
    if len(_io_loops) > 1:
        gen_log.warning("tornado.autoreload started more than once in the same process")
    modify_times = {}  # type: Dict[str, float]
    callback = functools.partial(_reload_on_update, modify_times)
    scheduler = ioloop.PeriodicCallback(callback, check_time)
    scheduler.start() 
Example #21
Source File: test_repoproviders.py    From binderhub with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_git_ref(url, unresolved_ref, resolved_ref):
    spec = '{}/{}'.format(
        quote(url, safe=''),
        quote(unresolved_ref)
    )

    provider = GitRepoProvider(spec=spec)
    slug = provider.get_build_slug()
    assert slug == url
    full_url = provider.get_repo_url()
    assert full_url == url
    ref = IOLoop().run_sync(provider.get_resolved_ref)
    assert ref == resolved_ref
    ref_url = IOLoop().run_sync(provider.get_resolved_ref_url)
    assert ref_url == full_url
    resolved_spec = IOLoop().run_sync(provider.get_resolved_spec)
    assert resolved_spec == quote(url, safe='') + f'/{resolved_ref}' 
Example #22
Source File: httpclient_test.py    From opendevops with GNU General Public License v3.0 6 votes vote down vote up
def setUp(self):
        self.server_ioloop = IOLoop()
        event = threading.Event()

        @gen.coroutine
        def init_server():
            sock, self.port = bind_unused_port()
            app = Application([("/", HelloWorldHandler)])
            self.server = HTTPServer(app)
            self.server.add_socket(sock)
            event.set()

        def start():
            self.server_ioloop.run_sync(init_server)
            self.server_ioloop.start()

        self.server_thread = threading.Thread(target=start)
        self.server_thread.start()
        event.wait()

        self.http_client = HTTPClient() 
Example #23
Source File: ioloop.py    From pySINDy with MIT License 5 votes vote down vote up
def instance(cls, *args, **kwargs):
        """Returns a global `IOLoop` instance.

        Most applications have a single, global `IOLoop` running on the
        main thread.  Use this method to get this instance from
        another thread.  To get the current thread's `IOLoop`, use `current()`.
        """
        # install ZMQIOLoop as the active IOLoop implementation
        # when using tornado 3
        ioloop.IOLoop.configure(cls)
        _deprecated()
        loop = ioloop.IOLoop.instance(*args, **kwargs)
        return loop 
Example #24
Source File: testing.py    From pySINDy with MIT License 5 votes vote down vote up
def get_new_ioloop(self):
        """Returns the `.IOLoop` to use for this test.

        By default, a new `.IOLoop` is created for each test.
        Subclasses may override this method to return
        `.IOLoop.current()` if it is not appropriate to use a new
        `.IOLoop` in each tests (for example, if there are global
        singletons using the default `.IOLoop`) or if a per-test event
        loop is being provided by another system (such as
        ``pytest-asyncio``).
        """
        return IOLoop() 
Example #25
Source File: test_tornado_acl.py    From python-consul2 with MIT License 5 votes vote down vote up
def loop():
    loop = ioloop.IOLoop()
    loop.make_current()
    return loop 
Example #26
Source File: autoreload.py    From pySINDy with MIT License 5 votes vote down vote up
def wait():
    """Wait for a watched file to change, then restart the process.

    Intended to be used at the end of scripts like unit test runners,
    to run the tests again after any source file changes (but see also
    the command-line interface in `main`)
    """
    io_loop = ioloop.IOLoop()
    io_loop.add_callback(start)
    io_loop.start() 
Example #27
Source File: ioloop.py    From pySINDy with MIT License 5 votes vote down vote up
def current(cls, *args, **kwargs):
        """Returns the current thread’s IOLoop.
        """
        # install ZMQIOLoop as the active IOLoop implementation
        # when using tornado 3
        ioloop.IOLoop.configure(cls)
        _deprecated()
        loop = ioloop.IOLoop.current(*args, **kwargs)
        return loop


# public API name 
Example #28
Source File: test_tornado.py    From python-consul with MIT License 5 votes vote down vote up
def loop():
    loop = ioloop.IOLoop()
    loop.make_current()
    return loop 
Example #29
Source File: ioloop.py    From pySINDy with MIT License 5 votes vote down vote up
def install():
    """DEPRECATED

    pyzmq 17 no longer needs any special integration for tornado.
    """
    _deprecated()
    ioloop.IOLoop.configure(ZMQIOLoop)


# if minitornado is used, fallback on deprecated ZMQIOLoop, install implementations 
Example #30
Source File: test_auth.py    From pySINDy with MIT License 5 votes vote down vote up
def setUp(self):
        try:
            from tornado import ioloop
        except ImportError:
            pytest.skip("Requires tornado")
        from zmq.eventloop import zmqstream
        self.fail_msg = None
        self.io_loop = ioloop.IOLoop()
        super(TestIOLoopAuthentication, self).setUp()
        self.server = self.socket(zmq.PUSH)
        self.client = self.socket(zmq.PULL)
        self.pushstream = zmqstream.ZMQStream(self.server, self.io_loop)
        self.pullstream = zmqstream.ZMQStream(self.client, self.io_loop)