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


Python concurrent.Future方法代码示例

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


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

示例1: wait_for_messages

# 需要导入模块: from tornado import concurrent [as 别名]
# 或者: from tornado.concurrent import Future [as 别名]
def wait_for_messages(self, cursor=None):
        # Construct a Future to return to our caller.  This allows
        # wait_for_messages to be yielded from a coroutine even though
        # it is not a coroutine itself.  We will set the result of the
        # Future when results are available.
        result_future = Future()
        if cursor:
            new_count = 0
            for msg in reversed(self.cache):
                if msg["id"] == cursor:
                    break
                new_count += 1
            if new_count:
                result_future.set_result(self.cache[-new_count:])
                return result_future
        self.waiters.add(result_future)
        return result_future 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:19,代码来源:chatdemo.py

示例2: maybe_future

# 需要导入模块: from tornado import concurrent [as 别名]
# 或者: from tornado.concurrent import Future [as 别名]
def maybe_future(x):
    """Converts ``x`` into a `.Future`.

    If ``x`` is already a `.Future`, it is simply returned; otherwise
    it is wrapped in a new `.Future`.  This is suitable for use as
    ``result = yield gen.maybe_future(f())`` when you don't know whether
    ``f()`` returns a `.Future` or not.

    .. deprecated:: 4.3
       This function only handles ``Futures``, not other yieldable objects.
       Instead of `maybe_future`, check for the non-future result types
       you expect (often just ``None``), and ``yield`` anything unknown.
    """
    if is_future(x):
        return x
    else:
        fut = Future()
        fut.set_result(x)
        return fut 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:21,代码来源:gen.py

示例3: sleep

# 需要导入模块: from tornado import concurrent [as 别名]
# 或者: from tornado.concurrent import Future [as 别名]
def sleep(duration):
    """Return a `.Future` that resolves after the given number of seconds.

    When used with ``yield`` in a coroutine, this is a non-blocking
    analogue to `time.sleep` (which should not be used in coroutines
    because it is blocking)::

        yield gen.sleep(0.5)

    Note that calling this function on its own does nothing; you must
    wait on the `.Future` it returns (usually by yielding it).

    .. versionadded:: 4.1
    """
    f = Future()
    IOLoop.current().call_later(duration, lambda: f.set_result(None))
    return f 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:19,代码来源:gen.py

示例4: convert_yielded

# 需要导入模块: from tornado import concurrent [as 别名]
# 或者: from tornado.concurrent import Future [as 别名]
def convert_yielded(yielded):
    """Convert a yielded object into a `.Future`.

    The default implementation accepts lists, dictionaries, and Futures.

    If the `~functools.singledispatch` library is available, this function
    may be extended to support additional types. For example::

        @convert_yielded.register(asyncio.Future)
        def _(asyncio_future):
            return tornado.platform.asyncio.to_tornado_future(asyncio_future)

    .. versionadded:: 4.1
    """
    # Lists and dicts containing YieldPoints were handled earlier.
    if isinstance(yielded, (list, dict)):
        return multi(yielded)
    elif is_future(yielded):
        return yielded
    elif isawaitable(yielded):
        return _wrap_awaitable(yielded)
    else:
        raise BadYieldError("yielded unknown object %r" % (yielded,)) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:25,代码来源:gen.py

示例5: wait

# 需要导入模块: from tornado import concurrent [as 别名]
# 或者: from tornado.concurrent import Future [as 别名]
def wait(self, timeout=None):
        """等待 `.notify`.

        返回一个 `.Future` 对象, 如果条件被通知则为 ``True`` ,
        或者在超时之后为 ``False`` .
        """
        waiter = Future()
        self._waiters.append(waiter)
        if timeout:
            def on_timeout():
                waiter.set_result(False)
                self._garbage_collect()
            io_loop = ioloop.IOLoop.current()
            timeout_handle = io_loop.add_timeout(timeout, on_timeout)
            waiter.add_done_callback(
                lambda _: io_loop.remove_timeout(timeout_handle))
        return waiter 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:19,代码来源:locks.py

示例6: test_moment

# 需要导入模块: from tornado import concurrent [as 别名]
# 或者: from tornado.concurrent import Future [as 别名]
def test_moment(self):
        calls = []

        @gen.coroutine
        def f(name, yieldable):
            for i in range(5):
                calls.append(name)
                yield yieldable
        # First, confirm the behavior without moment: each coroutine
        # monopolizes the event loop until it finishes.
        immediate = Future()
        immediate.set_result(None)
        yield [f('a', immediate), f('b', immediate)]
        self.assertEqual(''.join(calls), 'aaaaabbbbb')

        # With moment, they take turns.
        calls = []
        yield [f('a', gen.moment), f('b', gen.moment)]
        self.assertEqual(''.join(calls), 'ababababab')
        self.finished = True

        calls = []
        yield [f('a', gen.moment), f('b', immediate)]
        self.assertEqual(''.join(calls), 'abbbbbaaaa') 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:26,代码来源:gen_test.py

示例7: test_iterator

# 需要导入模块: from tornado import concurrent [as 别名]
# 或者: from tornado.concurrent import Future [as 别名]
def test_iterator(self):
        futures = [Future(), Future(), Future(), Future()]

        self.finish_coroutines(0, futures)

        g = gen.WaitIterator(*futures)

        i = 0
        while not g.done():
            try:
                r = yield g.next()
            except ZeroDivisionError:
                self.assertIs(g.current_future, futures[0],
                              'exception future invalid')
            else:
                if i == 0:
                    self.assertEqual(r, 24, 'iterator value incorrect')
                    self.assertEqual(g.current_index, 2, 'wrong index')
                elif i == 2:
                    self.assertEqual(r, 42, 'iterator value incorrect')
                    self.assertEqual(g.current_index, 1, 'wrong index')
                elif i == 3:
                    self.assertEqual(r, 84, 'iterator value incorrect')
                    self.assertEqual(g.current_index, 3, 'wrong index')
            i += 1 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:27,代码来源:gen_test.py

示例8: test_future_close_callback

# 需要导入模块: from tornado import concurrent [as 别名]
# 或者: from tornado.concurrent import Future [as 别名]
def test_future_close_callback(self):
        # Regression test for interaction between the Future read interfaces
        # and IOStream._maybe_add_error_listener.
        server, client = self.make_iostream_pair()
        closed = [False]

        def close_callback():
            closed[0] = True
            self.stop()
        server.set_close_callback(close_callback)
        try:
            client.write(b'a')
            future = server.read_bytes(1)
            self.io_loop.add_future(future, self.stop)
            self.assertEqual(self.wait().result(), b'a')
            self.assertFalse(closed[0])
            client.close()
            self.wait()
            self.assertTrue(closed[0])
        finally:
            server.close()
            client.close() 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:24,代码来源:iostream_test.py

示例9: setUp

# 需要导入模块: from tornado import concurrent [as 别名]
# 或者: from tornado.concurrent import Future [as 别名]
def setUp(self):
        try:
            super(TestIOStreamStartTLS, self).setUp()
            self.listener, self.port = bind_unused_port()
            self.server_stream = None
            self.server_accepted = Future()
            netutil.add_accept_handler(self.listener, self.accept)
            self.client_stream = IOStream(socket.socket())
            self.io_loop.add_future(self.client_stream.connect(
                ('127.0.0.1', self.port)), self.stop)
            self.wait()
            self.io_loop.add_future(self.server_accepted, self.stop)
            self.wait()
        except Exception as e:
            print(e)
            raise 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:18,代码来源:iostream_test.py

示例10: test_wait_for_handshake_future

# 需要导入模块: from tornado import concurrent [as 别名]
# 或者: from tornado.concurrent import Future [as 别名]
def test_wait_for_handshake_future(self):
        test = self
        handshake_future = Future()

        class TestServer(TCPServer):
            def handle_stream(self, stream, address):
                test.assertIsNone(stream.socket.cipher())
                test.io_loop.spawn_callback(self.handle_connection, stream)

            @gen.coroutine
            def handle_connection(self, stream):
                yield stream.wait_for_handshake()
                handshake_future.set_result(None)

        yield self.connect_to_server(TestServer)
        yield handshake_future 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:18,代码来源:iostream_test.py

示例11: test_wait_for_handshake_already_connected

# 需要导入模块: from tornado import concurrent [as 别名]
# 或者: from tornado.concurrent import Future [as 别名]
def test_wait_for_handshake_already_connected(self):
        handshake_future = Future()

        class TestServer(TCPServer):
            def handle_stream(self, stream, address):
                self.stream = stream
                stream.wait_for_handshake(self.handshake_done)

            def handshake_done(self):
                self.stream.wait_for_handshake(self.handshake2_done)

            def handshake2_done(self):
                handshake_future.set_result(None)

        yield self.connect_to_server(TestServer)
        yield handshake_future 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:18,代码来源:iostream_test.py

示例12: test_streaming_body

# 需要导入模块: from tornado import concurrent [as 别名]
# 或者: from tornado.concurrent import Future [as 别名]
def test_streaming_body(self):
        self.prepared = Future()
        self.data = Future()
        self.finished = Future()

        stream = self.connect(b"/stream_body", connection_close=True)
        yield self.prepared
        stream.write(b"4\r\nasdf\r\n")
        # Ensure the first chunk is received before we send the second.
        data = yield self.data
        self.assertEqual(data, b"asdf")
        self.data = Future()
        stream.write(b"4\r\nqwer\r\n")
        data = yield self.data
        self.assertEquals(data, b"qwer")
        stream.write(b"0\r\n")
        yield self.finished
        data = yield gen.Task(stream.read_until_close)
        # This would ideally use an HTTP1Connection to read the response.
        self.assertTrue(data.endswith(b"{}"))
        stream.close() 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:23,代码来源:web_test.py

示例13: write

# 需要导入模块: from tornado import concurrent [as 别名]
# 或者: from tornado.concurrent import Future [as 别名]
def write(self, chunk, callback=None):
        """Implements `.HTTPConnection.write`.

        For backwards compatibility is is allowed but deprecated to
        skip `write_headers` and instead call `write()` with a
        pre-encoded header block.
        """
        future = None
        if self.stream.closed():
            future = self._write_future = Future()
            self._write_future.set_exception(iostream.StreamClosedError())
            self._write_future.exception()
        else:
            if callback is not None:
                self._write_callback = stack_context.wrap(callback)
            else:
                future = self._write_future = Future()
            self._pending_write = self.stream.write(self._format_chunk(chunk))
            self._pending_write.add_done_callback(self._on_write_complete)
        return future 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:22,代码来源:http1connection.py

示例14: acquire

# 需要导入模块: from tornado import concurrent [as 别名]
# 或者: from tornado.concurrent import Future [as 别名]
def acquire(self, timeout=None):
        """递减计数器. 返回一个 Future 对象.

        如果计数器(counter)为0将会阻塞, 等待 `.release`. 在超时之后
        Future 对象将会抛出 `.TimeoutError` .
        """
        waiter = Future()
        if self._value > 0:
            self._value -= 1
            waiter.set_result(_ReleasingContextManager(self))
        else:
            self._waiters.append(waiter)
            if timeout:
                def on_timeout():
                    waiter.set_exception(gen.TimeoutError())
                    self._garbage_collect()
                io_loop = ioloop.IOLoop.current()
                timeout_handle = io_loop.add_timeout(timeout, on_timeout)
                waiter.add_done_callback(
                    lambda _: io_loop.remove_timeout(timeout_handle))
        return waiter 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:23,代码来源:locks.py

示例15: __init__

# 需要导入模块: from tornado import concurrent [as 别名]
# 或者: from tornado.concurrent import Future [as 别名]
def __init__(self, maxsize=0):
        if maxsize is None:
            raise TypeError("maxsize can't be None")

        if maxsize < 0:
            raise ValueError("maxsize can't be negative")

        self._maxsize = maxsize
        self._init()
        self._getters = collections.deque([])  # Futures.
        self._putters = collections.deque([])  # Pairs of (item, Future).
        self._unfinished_tasks = 0
        self._finished = Event()
        self._finished.set() 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:16,代码来源:queues.py


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