当前位置: 首页>>代码示例>>Python>>正文


Python IOLoop.stop方法代码示例

本文整理汇总了Python中tornado.ioloop.IOLoop.stop方法的典型用法代码示例。如果您正苦于以下问题:Python IOLoop.stop方法的具体用法?Python IOLoop.stop怎么用?Python IOLoop.stop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tornado.ioloop.IOLoop的用法示例。


在下文中一共展示了IOLoop.stop方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: SyncHTTPClientTest

# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import stop [as 别名]
class SyncHTTPClientTest(unittest.TestCase):
    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()

    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():
                # 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)

    def get_url(self, path):
        return "http://127.0.0.1:%d%s" % (self.port, path)

    def test_sync_client(self):
        response = self.http_client.fetch(self.get_url("/"))
        self.assertEqual(b"Hello world!", response.body)

    def test_sync_client_error(self):
        # Synchronous HTTPClient raises errors directly; no need for
        # response.rethrow()
        with self.assertRaises(HTTPError) as assertion:
            self.http_client.fetch(self.get_url("/notfound"))
        self.assertEqual(assertion.exception.code, 404)
开发者ID:rgbkrk,项目名称:tornado,代码行数:62,代码来源:httpclient_test.py

示例2: run_worker_fork

# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import stop [as 别名]
def run_worker_fork(q, ip, scheduler_ip, scheduler_port, ncores, nanny_port,
        worker_port, local_dir, services, name, memory_limit):
    """ Function run by the Nanny when creating the worker """
    from distributed import Worker  # pragma: no cover
    from tornado.ioloop import IOLoop  # pragma: no cover
    IOLoop.clear_instance()  # pragma: no cover
    loop = IOLoop()  # pragma: no cover
    loop.make_current()  # pragma: no cover
    worker = Worker(scheduler_ip, scheduler_port, ncores=ncores, ip=ip,
                    service_ports={'nanny': nanny_port}, local_dir=local_dir,
                    services=services, name=name, memory_limit=memory_limit,
                    loop=loop)  # pragma: no cover

    @gen.coroutine  # pragma: no cover
    def start():
        try:  # pragma: no cover
            yield worker._start(worker_port)  # pragma: no cover
        except Exception as e:  # pragma: no cover
            logger.exception(e)  # pragma: no cover
            q.put(e)  # pragma: no cover
        else:
            assert worker.port  # pragma: no cover
            q.put({'port': worker.port, 'dir': worker.local_dir})  # pragma: no cover

    loop.add_callback(start)  # pragma: no cover
    try:
        loop.start()  # pragma: no cover
    finally:
        loop.stop()
        loop.close(all_fds=True)
开发者ID:broxtronix,项目名称:distributed,代码行数:32,代码来源:nanny.py

示例3: Client

# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import stop [as 别名]
class Client(object):
    def __init__(self, host, port, timeout=None, connect_timeout=-1, unix_socket=None, max_buffer_size=104857600):
        self._io_loop = IOLoop()
        self._async_client = AsyncClient(host, port, unix_socket, self._io_loop, timeout, connect_timeout, max_buffer_size)
        self._response = None
        self._closed = False

    def __del__(self):
        self.close()

    @property
    def closed(self):
        return self._async_client.closed

    def close(self):
        if not self._closed:
            self._async_client.close()
            self._io_loop.close()
            self._closed = True

    def call(self, request):
        def callback(response):
            self._response = response
            self._io_loop.stop()
        self._async_client.call(request, callback)
        self._io_loop.start()
        response = self._response
        self._response = None
        response.rethrow()
        return response

    def __str__(self):
        return str(self._async_client)
开发者ID:gnap,项目名称:stpclient-py,代码行数:35,代码来源:client.py

示例4: HTTPClient

# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import stop [as 别名]
class HTTPClient(object):
    """ 阻塞式的HTTP客户端。使用ioloop+异步HTTP客户端实现,基本只是用于测试。 """
    def __init__(self, async_client_class=None, **kwargs):
        self._io_loop = IOLoop()
        if async_client_class is None:
            async_client_class = AsyncHTTPClient
        self._async_client = async_client_class(self._io_loop, **kwargs)
        self._response = None
        self._closed = False

    def __del__(self):
        self.close()

    def close(self):
        if not self._closed:
            self._async_client.close()
            self._io_loop.close()
            self._closed = True

    def fetch(self, request, **kwargs):
        def callback(response):
            self._response = response
            self._io_loop.stop()
        self._async_client.fetch(request, callback, **kwargs)
        self._io_loop.start()
        response = self._response
        self._response = None
        response.rethrow()
        return response
开发者ID:effyroth,项目名称:tornado-src-comment,代码行数:31,代码来源:httpclient.py

示例5: loop

# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import stop [as 别名]
def loop():
    IOLoop.clear_instance()
    loop = IOLoop()
    loop.make_current()
    yield loop
    loop.stop()
    loop.close()
开发者ID:canavandl,项目名称:distributed,代码行数:9,代码来源:utils_test.py

示例6: SocketServerThreadStarter

# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import stop [as 别名]
class SocketServerThreadStarter(Thread):
    '''
    Used to fire up the three services each in its own thread.
    '''
    
    def __init__(self, socketServerClassName, port):
        '''
        Create one thread for one of the services to run in.
        @param socketServerClassName: Name of top level server class to run.
        @type socketServerClassName: string
        @param port: port to listen on
        @type port: int
        '''
        super(SocketServerThreadStarter, self).__init__();
        self.socketServerClassName = socketServerClassName;
        self.port = port;
        self.ioLoop = None;

    def stop(self):
        self.ioLoop.stop();
       
    def run(self):
        '''
        Use the service name to instantiate the proper service, passing in the
        proper helper class.
        '''
        super(SocketServerThreadStarter, self).run();
        try:
            if  self.socketServerClassName == 'RootWordSubmissionService':
                EchoTreeService.log("Starting EchoTree new tree submissions server %d: accepts word trees submitted from connecting clients." % self.port);
                http_server = RootWordSubmissionService(RootWordSubmissionService.handle_request);
                http_server.listen(self.port);
                self.ioLoop = IOLoop();
                self.ioLoop.start();
                self.ioLoop.close(all_fds=True);
                return;
            elif self.socketServerClassName == 'EchoTreeScriptRequestHandler':
                EchoTreeService.log("Starting EchoTree script server %d: Returns one script that listens to the new-tree events in the browser." % self.port);
                http_server = EchoTreeScriptRequestHandler(EchoTreeScriptRequestHandler.handle_request);
                http_server.listen(self.port);
                self.ioLoop = IOLoop();
                self.ioLoop.start();
                self.ioLoop.close(all_fds=True);
                return;
            else:
                raise ValueError("Service class %s is unknown." % self.socketServerClassName);
        except Exception:
            # Typically an exception is caught here that complains about 'socket in use'
            # Should avoid that by sensing busy socket and timing out:
#            if e.errno == 98:
#                print "Exception: %s. You need to try starting this service again. Socket busy condition will time out within 30 secs or so." % `e`
#            else:
#                print `e`;
            #raise e;
            pass
        finally:
            if self.ioLoop is not None and self.ioLoop.running():
                self.ioLoop.stop();
                return;
开发者ID:imclab,项目名称:echo_tree,代码行数:61,代码来源:echo_tree_server.py

示例7: XDebugServer

# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import stop [as 别名]
class XDebugServer(TCPServer):

    """Class to listen for xdebug requests"""

    def __init__(self):
        """Constructor """
        self.ioloop = IOLoop()
        super(XDebugServer, self).__init__(io_loop=self.ioloop)

        self.listen(9000)

        # this is for cross thread communication
        self.inport = Queue()
        self.outport = Queue()

        self._xdebug_connection = None

        def listenfunc():
            self.ioloop.make_current()
            self.ioloop.start()
            self.ioloop.close(all_fds=True)

        self.listener_thread = threading.Thread(target=listenfunc)
        self.listener_thread.daemon = True
        self.listener_thread.start()


    def handle_stream(self, stream, address):
        """Handle a connection

        Only one connection at a time, for now

        :stream: @todo
        :address: @todo
        :returns: @todo

        """
        self._xdebug_connection = XDebugConnection(self, stream, address)

    def run_command(self, command, data=None):
        """Send status
        :returns: @todo

        """
        self.inport.put("{} -i 1\0".format(str(command)))
        return self.outport.get()
        

    def stop(self):
        """Stop tornado event loop
        :returns: @todo

        """
        self.ioloop.stop()
        self.listener_thread.join()

        del self.ioloop
        del self.listener_thread
开发者ID:jupake,项目名称:myvim,代码行数:60,代码来源:xdebugserver.py

示例8: TestGitHubParser

# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import stop [as 别名]
class TestGitHubParser(TestCase, TimeoutMixin):

    def setUp(self):
        self._ioloop = IOLoop()

    def test_github_parser(self):
        result = {}
        def callback(commit_result):
            for key in commit_result:
                result[key] = commit_result[key]
            self._ioloop.stop()

        github_parser = GitHubParser(self._ioloop, {})
        github_parser.parse("https://github.com/julython/"
            "julythontweets/commit/25645d2cf6b58d2657cf6eb0fb4ca59d5f2499f4",
            callback)

        self.add_timeout(3)
        self._ioloop.start()
        # will block until callback or timeout
        self.assertEqual("Josh Marshall",
            result["author"]["name"])
        self.assertEqual("joshmarshall",
            result["author"]["username"])
        self.assertEqual(
            "25645d2cf6b58d2657cf6eb0fb4ca59d5f2499f4",
            result["commit"])

    def test_get_commit_atom_link(self):
        """Test extracting commit Atom URL from an HTML page."""
        with self.assertRaises(MissingAtomLink):
            get_commit_atom_link("WHATEVER")
        with self.assertRaises(MissingAtomLink):
            get_commit_atom_link("<html></html>")
        html = open(_GITHUB_SAMPLE_HTML_PATH).read()
        atom_link = get_commit_atom_link(html)
        self.assertEqual(
            "https://github.com/julython/julythontweets/commits/master.atom",
            atom_link)

    def test_get_most_recent_commit(self):
        """Test extracting most recent commit from an Atom Feed."""
        with self.assertRaises(MissingCommit):
            get_most_recent_commit("whatever")
        with self.assertRaises(MissingCommit):
            get_most_recent_commit("<rss></rss>")
        feed = open(_GITHUB_SAMPLE_ATOM_PATH).read()
        commit = get_most_recent_commit(feed)
        self.assertEqual({
                "name": "Josh Marshall",
                "url": "https://github.com/joshmarshall",
                "username": "joshmarshall",
                "service": "github"
            }, commit["author"])
        self.assertEqual("25645d2cf6b58d2657cf6eb0fb4ca59d5f2499f4",
            commit["commit"])
        self.assertEqual("julython/julythontweets", commit["project"]["id"])
        self.assertEqual("github", commit["project"]["service"])
开发者ID:julython,项目名称:julythontweets,代码行数:60,代码来源:test_github_parser.py

示例9: TornadoFlask

# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import stop [as 别名]
class TornadoFlask(Flask):
    def run(self, host='0.0.0.0', port=5000):
        self.ioloop = IOLoop()
        http_server = HTTPServer(WSGIContainer(app), io_loop=self.ioloop)
        http_server.listen(port, host)
        self.ioloop.start()

    def quit(self):
        self.ioloop.stop()
开发者ID:CKAKA,项目名称:pyspider,代码行数:11,代码来源:app.py

示例10: test_func

# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import stop [as 别名]
        def test_func():
            IOLoop.clear_instance()
            loop = IOLoop()
            loop.make_current()

            cor = gen.coroutine(func)
            try:
                loop.run_sync(cor, timeout=timeout)
            finally:
                loop.stop()
                loop.close(all_fds=True)
开发者ID:danring,项目名称:distributed,代码行数:13,代码来源:utils_test.py

示例11: HTTPClient

# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import stop [as 别名]
class HTTPClient(object):
    """A blocking HTTP client.

    This interface is provided for convenience and testing; most applications
    that are running an IOLoop will want to use `AsyncHTTPClient` instead.
    Typical usage looks like this::

        http_client = httpclient.HTTPClient()
        try:
            response = http_client.fetch("http://www.google.com/")
            print response.body
        except httpclient.HTTPError, e:
            print "Error:", e
    """

    def __init__(self, async_client_class=None, **kwargs):
        self._io_loop = IOLoop()
        if async_client_class is None:
            async_client_class = AsyncHTTPClient
        self._async_client = async_client_class(self._io_loop, **kwargs)
        self._response = None
        self._closed = False

    def __del__(self):
        self.close()

    def close(self):
        """Closes the HTTPClient, freeing any resources used."""
        if not self._closed:
            self._async_client.close()
            self._io_loop.close()
            self._closed = True

    def fetch(self, request, **kwargs):
        """Executes a request, returning an `HTTPResponse`.

        The request may be either a string URL or an `HTTPRequest` object.
        If it is a string, we construct an `HTTPRequest` using any additional
        kwargs: ``HTTPRequest(request, **kwargs)``

        If an error occurs during the fetch, we raise an `HTTPError`.
        """

        def callback(response):
            self._response = response
            self._io_loop.stop()

        self._async_client.fetch(request, callback, **kwargs)
        self._io_loop.start()
        response = self._response
        self._response = None
        response.rethrow()
        return response
开发者ID:velsa,项目名称:edtr.me,代码行数:55,代码来源:httpclient.py

示例12: test_func

# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import stop [as 别名]
        def test_func():
            IOLoop.clear_instance()
            loop = IOLoop()
            loop.make_current()

            s, workers = loop.run_sync(lambda: start_cluster(ncores))
            try:
                loop.run_sync(lambda: cor(s, *workers), timeout=timeout)
            finally:
                loop.run_sync(lambda: end_cluster(s, workers))
                loop.stop()
                loop.close()
开发者ID:lucashtnguyen,项目名称:distributed,代码行数:14,代码来源:utils_test.py

示例13: main

# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import stop [as 别名]
def main(args=None):
    if args is None:
        args = sys.argv

    setup_logger()

    router = TornadioRouter(RouterConnection)

    bg_loop = IOLoop()
    bg_thread = Thread(target=lambda: bg_loop.start())
    bg_task = task.Task(bg_loop)

    application = Application(
        router.apply_routes([
            (r"/", IndexHandler),
            (r"/start", StartHandler),
            (r"/start_mission", StartMissionHandler),
        ]),
        debug=True,
    )

    application.listen(8000)

    StartHandler.triggered.connect(bg_task.setup_api)
    StartMissionHandler.triggered.connect(bg_task.start_mission)
    event.api_started.connect(RouterConnection.on_api_started)
    event.mission_started.connect(RouterConnection.on_mission_started)
    event.mission_result.connect(RouterConnection.on_mission_result)

    try:
        bg_thread.start()
        IOLoop.instance().start()
    except KeyboardInterrupt:
        bg_loop.stop()
        IOLoop.instance().stop()

    # api_token = args[1]

    # client_ = client.Client(api_token)
    # event_loop = tornado.ioloop.IOLoop()
    # event_loop = task.EventLoop()

    # mission = client.Mission(client=client_, event_loop=event_loop)
    # mission.start(api_deck_id=2, api_mission_id=5)
    # mission.start(api_deck_id=3, api_mission_id=21)
    # mission.start(api_deck_id=4, api_mission_id=38)

    # nyukyo = client.Nyukyo(client=client_, event_loop=event_loop)
    # nyukyo.start()

    # event_loop.start()

    return 0
开发者ID:legnaleurc,项目名称:kcapi,代码行数:55,代码来源:__main__.py

示例14: FakeServerContext

# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import stop [as 别名]
class FakeServerContext(object):
    def __init__(self, monkeypatch, fail_these, expected_basename):
        self._monkeypatch = monkeypatch
        self._fail_these = fail_these
        self._expected_basename = expected_basename
        self._url = None
        self._loop = None
        self._started = threading.Condition()
        self._thread = threading.Thread(target=self._run)

    def __exit__(self, type, value, traceback):
        if self._loop is not None:
            # we can ONLY use add_callback here, since the loop is
            # running in a different thread.
            self._loop.add_callback(self._stop)
        self._thread.join()

    def __enter__(self):
        self._started.acquire()
        self._thread.start()
        self._started.wait()
        self._started.release()
        _monkeypatch_client_config(self._monkeypatch, self._url)
        return self._url

    def _run(self):
        self._loop = IOLoop()
        self._server = FakeAnacondaServer(io_loop=self._loop,
                                          fail_these=self._fail_these,
                                          expected_basename=self._expected_basename)
        self._url = self._server.url

        def notify_started():
            self._started.acquire()
            self._started.notify()
            self._started.release()

        self._loop.add_callback(notify_started)
        self._loop.start()
        # done
        self._server.unlisten()

    def _stop(self):
        def really_stop():
            if self._loop is not None:
                self._loop.stop()
                self._loop = None
        # the delay allows pending next-tick things to go ahead
        # and happen, which may avoid some problems with trying to
        # output to stdout after pytest closes it
        if self._loop is not None:
            self._loop.call_later(delay=0.05, callback=really_stop)
开发者ID:conda,项目名称:kapsel,代码行数:54,代码来源:fake_server.py

示例15: TestIOLoopCurrent

# 需要导入模块: from tornado.ioloop import IOLoop [as 别名]
# 或者: from tornado.ioloop.IOLoop import stop [as 别名]
class TestIOLoopCurrent(unittest.TestCase):
    def setUp(self):
        self.io_loop = IOLoop()

    def tearDown(self):
        self.io_loop.close()

    def test_current(self):
        def f():
            self.current_io_loop = IOLoop.current()
            self.io_loop.stop()
        self.io_loop.add_callback(f)
        self.io_loop.start()
        self.assertIs(self.current_io_loop, self.io_loop)
开发者ID:EliseCheng,项目名称:tornado,代码行数:16,代码来源:ioloop_test.py


注:本文中的tornado.ioloop.IOLoop.stop方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。