Python asyncio 模块,Future() 实例源码

我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用asyncio.Future()

项目:Daniel-Arbuckles-Mastering-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def zoo():
    scheduler = rx.concurrency.AsyncIOScheduler()

    elephant = Animal('Lucretia', 'trumpets').as_observable(scheduler)
    lion = Animal('Arnold', 'roars').as_observable(scheduler)
    fox = Animal('Betty', 'goes chacha-chacha-chacha-chow').as_observable(scheduler)
    snake = Animal('Jake', 'hisses').as_observable(scheduler)

    louder = rx.Observable.merge(elephant, lion).select(sometimes_loud)

    out = rx.Observable.merge(fox, snake, louder).do_action(on_next = output)

    done = asyncio.Future()

    out.subscribe(on_completed = (lambda: done.set_result(True)))

    return done
项目:PyPlanet    作者:PyPlanet    | 项目源码 | 文件源码
def execute(self):
        """
        Execute call.

        :return: Future with results.
        :rtype: Future<any>
        """
        # Create new future to be returned. This future will be the answered inside a script callback.
        future = None
        if self.response_id:
            self._client.script_handlers[self.response_id] = future = asyncio.Future()

        # Execute the call itself and register the callback script handler.
        gbx_res = await self._client.execute(self.method, *self.args)

        if self.response_id:
            return await asyncio.wait_for(future, self.timeout) # Timeout after 15 seconds!
        return gbx_res
项目:PyPlanet    作者:PyPlanet    | 项目源码 | 文件源码
def __init__(self, parent, player, setting):
        """
        Initiate child edit view.

        :param parent: Parent view.
        :param player: Player instance.
        :param setting: Setting instance.
        :type parent: pyplanet.view.base.View
        :type player: pyplanet.apps.core.maniaplanet.models.player.Player
        :type setting: pyplanet.contrib.setting.setting.Setting
        """
        super().__init__(parent.manager)
        self.parent = parent
        self.player = player
        self.setting = setting

        self.response_future = asyncio.Future()

        self.subscribe('button_close', self.close)
        self.subscribe('button_save', self.save)
        self.subscribe('button_cancel', self.close)
项目:PyPlanet    作者:PyPlanet    | 项目源码 | 文件源码
def __init__(self, parent, player, folder_manager):
        """
        Initiate child create view.

        :param parent: Parent view.
        :param player: Player instance.
        :param folder_manager: Folder manager instance.
        :type parent: pyplanet.view.base.View
        :type player: pyplanet.apps.core.maniaplanet.models.player.Player
        :type folder_manager: pyplanet.apps.contrib.jukebox.folders.FolderManager
        """
        super().__init__(parent.manager)

        self.parent = parent
        self.player = player
        self.folder_manager = folder_manager
        self.app = folder_manager.app

        self.response_future = asyncio.Future()

        self.subscribe('button_close', self.close)
        self.subscribe('button_save', self.save)
        self.subscribe('button_cancel', self.close)
项目:PyPlanet    作者:PyPlanet    | 项目源码 | 文件源码
def __init__(self, parent, player, setting):
        """
        Initiate child edit view.

        :param parent: Parent view.
        :param player: Player instance.
        :param setting: Setting dictionary.
        :type parent: pyplanet.view.base.View
        :type player: pyplanet.apps.core.maniaplanet.models.player.Player
        :type setting: dict
        """
        super().__init__(parent.manager)
        self.parent = parent
        self.player = player
        self.setting = setting

        self.response_future = asyncio.Future()

        self.subscribe('button_close', self.close)
        self.subscribe('button_save', self.save)
        self.subscribe('button_cancel', self.close)
项目:PyPlanet    作者:PyPlanet    | 项目源码 | 文件源码
def show_alert(player, message, size='md', buttons=None):  # pragma: no cover
    """
    Show an alert to the player with given details. This is a shortcut method for the class itself.

    :param player: Player login or instance.
    :param message: Message in string.
    :param size: Size, could be 'sm', 'md', or 'lg'.
    :param buttons: Buttons, optional, default is 'OK'.
    :return: Number of the clicked button. (in Future).
    """
    buttons = buttons or [{'name': 'OK'}]
    view = AlertView(message, size, buttons)
    if isinstance(player, Player):
        player = player.login
    await view.display(player_logins=[player])
    reaction = await view.wait_for_reaction()
    try:
        reaction = int(reaction)
    except:
        reaction = None
    del view
    return reaction
项目:pyppeteer    作者:miyakogi    | 项目源码 | 文件源码
def __init__(self, client: Session, ignoreHTTPSErrors: Any,
                 options: dict = None, **kwargs: Any) -> None:
        """Make new navigator watcher."""
        if options is None:
            options = {}
        options.update(kwargs)
        self._client = client
        self._ignoreHTTPSErrors = ignoreHTTPSErrors
        self._timeout = options.get('timeout', 3000)
        self._idleTime = options.get('networkIdleTimeout', 1000)
        self._idleTimer: Optional[Union[asyncio.Future, asyncio.Handle]] = None
        self._idleInflight = options.get('networkIdleInflight', 2)
        self._waitUntil = options.get('waitUntil', 'load')
        if self._waitUntil not in ('load', 'networkidle'):
            raise ValueError(
                f'Unknown value for options.waitUntil: {self._waitUntil}')
项目:pyppeteer    作者:miyakogi    | 项目源码 | 文件源码
def __init__(self, url: str, delay: int = 0) -> None:
        """Make connection.

        :arg str url: WebSocket url to connect devtool.
        :arg int delay: delay to wait until send messages.
        """
        super().__init__()
        self._url = url
        self._lastId = 0
        self._callbacks: Dict[int, asyncio.Future] = dict()
        self._delay = delay
        self._sessions: Dict[str, Session] = dict()
        self.connection: Session
        self._connected = False
        self._ws = websockets.client.connect(self._url)
        self._recv_fut = asyncio.ensure_future(self._recv_loop())
项目:CEX.IO-Client-Python3.5    作者:cexioltd    | 项目源码 | 文件源码
def _test_message_id_resolver1(self):

        resolver = RequestResponseFutureResolver(name='', op_name_get_path='e',
                                                    key_get_path='id', key_set_path='id')
        f1 = asyncio.Future()
        f2 = asyncio.Future()
        message = resolver.mark(            {'root': {'message': {'m': 'message_to_send 1', }, }, 'e': 'op_name', }, f1)
        id1 = message['id']
        message = resolver.mark(            {'root': {'message': {'m': 'message_to_send 2', }, }, 'e': 'op_name', }, f2)
        id2 = message['id']

        with self.subTest(key_set_path='id', key_get_path='id', next=None):
            # resolved
            result = await resolver(            {'message': {'m': 'message_received 1', }, 'id': id1})
            self.assertEqual(f1.result(),       {'message': {'m': 'message_received 1', }, 'id': id1})
            self.assertEqual(result,            {'message': {'m': 'message_received 1', }, 'id': id1})

            # can not be resolved twice
            result = await resolver(            {'message': {'m': 'message_received 1', }, 'id': id1})
            self.assertIsNone(result)

            # resolved
            result = await resolver(            {'message': {'m': 'message_received 2', }, 'id': id2})
            self.assertEqual(f2.result(),       {'message': {'m': 'message_received 2', }, 'id': id2})
            self.assertEqual(result,            {'message': {'m': 'message_received 2', }, 'id': id2})
项目:CEX.IO-Client-Python3.5    作者:cexioltd    | 项目源码 | 文件源码
def _test_message_id_resolver2(self):

        resolver = RequestResponseFutureResolver(name='', op_name_get_path='e',
                                                    key_get_path='message/id', key_set_path='root/message/id')
        f1 = asyncio.Future()
        f2 = asyncio.Future()
        message = resolver.mark(            {'root': {'message': {'m': 'message_to_send 1', }, }, 'e': 'op_name', }, f1)
        id1 = message['root']['message']['id']
        message = resolver.mark(            {'root': {'message': {'m': 'message_to_send 2', }, }, 'e': 'op_name', }, f2)
        id2 = message['root']['message']['id']

        with self.subTest(key_set_path='root/message/id', key_get_path='message/id', next=None):
            # resolved
            result = await resolver(            {'message': {'m': 'message_received 1', 'id': id1, }, })
            self.assertEqual(f1.result(),       {'message': {'m': 'message_received 1', 'id': id1, }, })
            self.assertEqual(result,            {'message': {'m': 'message_received 1', 'id': id1, }, })

            # can not be resolved twice
            result = await resolver(            {'message': {'m': 'message_received 1', 'id': id1, }, })
            self.assertIsNone(result)

            # resolved
            result = await resolver(            {'message': {'m': 'message_received 2', 'id': id2, }, })
            self.assertEqual(f2.result(),       {'message': {'m': 'message_received 2', 'id': id2, }, })
            self.assertEqual(result,            {'message': {'m': 'message_received 2', 'id': id2, }, })
项目:trellio    作者:artificilabs    | 项目源码 | 文件源码
def _send_request(self, app_name, endpoint, entity, params, timeout):
        packet = MessagePacket.request(self.name, self.version, app_name, _Service._REQ_PKT_STR, endpoint, params,
                                       entity)
        future = Future()
        request_id = params['request_id']
        self._pending_requests[request_id] = future
        try:
            self.tcp_bus.send(packet)
        except ClientException:
            if not future.done() and not future.cancelled():
                error = 'Client not found'
                exception = ClientException(error)
                exception.error = error
                future.set_exception(exception)
        _Service.time_future(future, timeout)
        return future
项目:oshino    作者:CodersOfTheNight    | 项目源码 | 文件源码
def flush(client, transport, logger):
    future = asyncio.Future()

    async def process_async(future):
        try:
            transport.connect()
            client.flush()
            transport.disconnect()

            future.set_result(True)
        except ConnectionRefusedError as ce:
            logger.warn(ce)

            future.set_result(False)

    asyncio.ensure_future(process_async(future))
    await future
    return future.result()
项目:chrome-prerender    作者:bosondata    | 项目源码 | 文件源码
def _listen(self) -> None:
        tasks: List[Future] = []

        def _on_task_done(task: Future) -> None:
            tasks.remove(task)
            if not task.cancelled() and task.exception():
                self._render_future.set_exception(task.exception())

        try:
            while True:
                task = await self.recv()
                task.add_done_callback(_on_task_done)
                tasks.append(task)
        finally:
            for task in tasks:
                task.cancel()
项目:pymotw3    作者:reingart    | 项目源码 | 文件源码
def run_df(loop):
    print('in run_df')

    cmd_done = asyncio.Future(loop=loop)
    factory = functools.partial(DFProtocol, cmd_done)
    proc = loop.subprocess_exec(
        factory,
        'df', '-hl',
        stdin=None,
        stderr=None,
    )
    try:
        print('launching process')
        transport, protocol = await proc
        print('waiting for process to complete')
        await cmd_done
    finally:
        transport.close()

    return cmd_done.result()
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_pause_writing_3write(self):
        tr = self.pause_writing_transport(high=4)

        # first short write, the buffer is not full (1 <= 4)
        fut = asyncio.Future(loop=self.loop)
        self.loop._proactor.send.return_value = fut
        tr.write(b'1')
        self.loop._run_once()
        self.assertEqual(tr.get_write_buffer_size(), 1)
        self.assertFalse(self.protocol.pause_writing.called)

        # second short write, the buffer is not full (3 <= 4)
        tr.write(b'23')
        self.loop._run_once()
        self.assertEqual(tr.get_write_buffer_size(), 3)
        self.assertFalse(self.protocol.pause_writing.called)

        # fill the buffer, must pause writing (6 > 4)
        tr.write(b'abc')
        self.loop._run_once()
        self.assertEqual(tr.get_write_buffer_size(), 6)
        self.assertTrue(self.protocol.pause_writing.called)
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_create_server_sock(self):
        proto = asyncio.Future(loop=self.loop)

        class TestMyProto(MyProto):
            def connection_made(self, transport):
                super().connection_made(transport)
                proto.set_result(self)

        sock_ob = socket.socket(type=socket.SOCK_STREAM)
        sock_ob.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock_ob.bind(('0.0.0.0', 0))

        f = self.loop.create_server(TestMyProto, sock=sock_ob)
        server = self.loop.run_until_complete(f)
        sock = server.sockets[0]
        self.assertIs(sock, sock_ob)

        host, port = sock.getsockname()
        self.assertEqual(host, '0.0.0.0')
        client = socket.socket()
        client.connect(('127.0.0.1', port))
        client.send(b'xxx')
        client.close()
        server.close()
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test__sock_connect_writer(self):
        # check that the fd is registered and then unregistered
        self.loop._process_events = mock.Mock()
        self.loop.add_writer = mock.Mock()
        self.loop.remove_writer = mock.Mock()

        sock = mock.Mock()
        sock.fileno.return_value = 10
        sock.connect.side_effect = BlockingIOError
        sock.getsockopt.return_value = 0
        address = ('127.0.0.1', 8080)

        f = asyncio.Future(loop=self.loop)
        self.loop._sock_connect(f, sock, address)
        self.assertTrue(self.loop.add_writer.called)
        self.assertEqual(10, self.loop.add_writer.call_args[0][0])

        self.loop._sock_connect_cb(f, sock, address)
        # need to run the event loop to execute _sock_connect_done() callback
        self.loop.run_until_complete(f)
        self.assertEqual((10,), self.loop.remove_writer.call_args[0])
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_cancel_handshake(self):
        # Python issue #23197: cancelling an handshake must not raise an
        # exception or log an error, even if the handshake failed
        waiter = asyncio.Future(loop=self.loop)
        ssl_proto = self.ssl_protocol(waiter)
        handshake_fut = asyncio.Future(loop=self.loop)

        def do_handshake(callback):
            exc = Exception()
            callback(exc)
            handshake_fut.set_result(None)
            return []

        waiter.cancel()
        self.connection_made(ssl_proto, do_handshake)

        with test_utils.disable_logger():
            self.loop.run_until_complete(handshake_fut)
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_proc_exited(self):
        waiter = asyncio.Future(loop=self.loop)
        transport, protocol = self.create_transport(waiter)
        transport._process_exited(6)
        self.loop.run_until_complete(waiter)

        self.assertEqual(transport.get_returncode(), 6)

        self.assertTrue(protocol.connection_made.called)
        self.assertTrue(protocol.process_exited.called)
        self.assertTrue(protocol.connection_lost.called)
        self.assertEqual(protocol.connection_lost.call_args[0], (None,))

        self.assertFalse(transport._closed)
        self.assertIsNone(transport._loop)
        self.assertIsNone(transport._proc)
        self.assertIsNone(transport._protocol)

        # methods must raise ProcessLookupError if the process exited
        self.assertRaises(ProcessLookupError,
                          transport.send_signal, signal.SIGTERM)
        self.assertRaises(ProcessLookupError, transport.terminate)
        self.assertRaises(ProcessLookupError, transport.kill)

        transport.close()
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_yield_from_twice(self):
        f = asyncio.Future(loop=self.loop)

        def fixture():
            yield 'A'
            x = yield from f
            yield 'B', x
            y = yield from f
            yield 'C', y

        g = fixture()
        self.assertEqual(next(g), 'A')  # yield 'A'.
        self.assertEqual(next(g), f)  # First yield from f.
        f.set_result(42)
        self.assertEqual(next(g), ('B', 42))  # yield 'B', x.
        # The second "yield from f" does not yield f.
        self.assertEqual(next(g), ('C', 42))  # yield 'C', y.
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_copy_state(self):
        # Test the internal _copy_state method since it's being directly
        # invoked in other modules.
        f = asyncio.Future(loop=self.loop)
        f.set_result(10)

        newf = asyncio.Future(loop=self.loop)
        newf._copy_state(f)
        self.assertTrue(newf.done())
        self.assertEqual(newf.result(), 10)

        f_exception = asyncio.Future(loop=self.loop)
        f_exception.set_exception(RuntimeError())

        newf_exception = asyncio.Future(loop=self.loop)
        newf_exception._copy_state(f_exception)
        self.assertTrue(newf_exception.done())
        self.assertRaises(RuntimeError, newf_exception.result)

        f_cancelled = asyncio.Future(loop=self.loop)
        f_cancelled.cancel()

        newf_cancelled = asyncio.Future(loop=self.loop)
        newf_cancelled._copy_state(f_cancelled)
        self.assertTrue(newf_cancelled.cancelled())
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_async_future(self):
        f_orig = asyncio.Future(loop=self.loop)
        f_orig.set_result('ko')

        f = asyncio.async(f_orig)
        self.loop.run_until_complete(f)
        self.assertTrue(f.done())
        self.assertEqual(f.result(), 'ko')
        self.assertIs(f, f_orig)

        loop = asyncio.new_event_loop()
        self.set_event_loop(loop)

        with self.assertRaises(ValueError):
            f = asyncio.async(f_orig, loop=loop)

        loop.close()

        f = asyncio.async(f_orig, loop=self.loop)
        self.assertIs(f, f_orig)
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_cancel_task_catching(self):
        fut1 = asyncio.Future(loop=self.loop)
        fut2 = asyncio.Future(loop=self.loop)

        @asyncio.coroutine
        def task():
            yield from fut1
            try:
                yield from fut2
            except asyncio.CancelledError:
                return 42

        t = asyncio.Task(task(), loop=self.loop)
        test_utils.run_briefly(self.loop)
        self.assertIs(t._fut_waiter, fut1)  # White-box test.
        fut1.set_result(None)
        test_utils.run_briefly(self.loop)
        self.assertIs(t._fut_waiter, fut2)  # White-box test.
        t.cancel()
        self.assertTrue(fut2.cancelled())
        res = self.loop.run_until_complete(t)
        self.assertEqual(res, 42)
        self.assertFalse(t.cancelled())
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_task_cancel_waiter_future(self):
        fut = asyncio.Future(loop=self.loop)

        @asyncio.coroutine
        def coro():
            yield from fut

        task = asyncio.Task(coro(), loop=self.loop)
        test_utils.run_briefly(self.loop)
        self.assertIs(task._fut_waiter, fut)

        task.cancel()
        test_utils.run_briefly(self.loop)
        self.assertRaises(
            asyncio.CancelledError, self.loop.run_until_complete, task)
        self.assertIsNone(task._fut_waiter)
        self.assertTrue(fut.cancelled())
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_coroutine_non_gen_function_return_future(self):
        fut = asyncio.Future(loop=self.loop)

        @asyncio.coroutine
        def func():
            return fut

        @asyncio.coroutine
        def coro():
            fut.set_result('test')

        t1 = asyncio.Task(func(), loop=self.loop)
        t2 = asyncio.Task(coro(), loop=self.loop)
        res = self.loop.run_until_complete(t1)
        self.assertEqual(res, 'test')
        self.assertIsNone(t2.result())
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_shield_effect(self):
        # Cancelling outer() does not affect inner().
        proof = 0
        waiter = asyncio.Future(loop=self.loop)

        @asyncio.coroutine
        def inner():
            nonlocal proof
            yield from waiter
            proof += 1

        @asyncio.coroutine
        def outer():
            nonlocal proof
            yield from asyncio.shield(inner(), loop=self.loop)
            proof += 100

        f = asyncio.async(outer(), loop=self.loop)
        test_utils.run_briefly(self.loop)
        f.cancel()
        with self.assertRaises(asyncio.CancelledError):
            self.loop.run_until_complete(f)
        waiter.set_result(None)
        test_utils.run_briefly(self.loop)
        self.assertEqual(proof, 1)
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_yield_from_corowrapper(self):
        old_debug = asyncio.coroutines._DEBUG
        asyncio.coroutines._DEBUG = True
        try:
            @asyncio.coroutine
            def t1():
                return (yield from t2())

            @asyncio.coroutine
            def t2():
                f = asyncio.Future(loop=self.loop)
                asyncio.Task(t3(f), loop=self.loop)
                return (yield from f)

            @asyncio.coroutine
            def t3(f):
                f.set_result((1, 2, 3))

            task = asyncio.Task(t1(), loop=self.loop)
            val = self.loop.run_until_complete(task)
            self.assertEqual(val, (1, 2, 3))
        finally:
            asyncio.coroutines._DEBUG = old_debug
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_one_exception(self):
        a, b, c, d, e = [asyncio.Future(loop=self.one_loop) for i in range(5)]
        fut = asyncio.gather(*self.wrap_futures(a, b, c, d, e))
        cb = test_utils.MockCallback()
        fut.add_done_callback(cb)
        exc = ZeroDivisionError()
        a.set_result(1)
        b.set_exception(exc)
        self._run_loop(self.one_loop)
        self.assertTrue(fut.done())
        cb.assert_called_once_with(fut)
        self.assertIs(fut.exception(), exc)
        # Does nothing
        c.set_result(3)
        d.cancel()
        e.set_exception(RuntimeError())
        e.exception()
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_return_exceptions(self):
        a, b, c, d = [asyncio.Future(loop=self.one_loop) for i in range(4)]
        fut = asyncio.gather(*self.wrap_futures(a, b, c, d),
                             return_exceptions=True)
        cb = test_utils.MockCallback()
        fut.add_done_callback(cb)
        exc = ZeroDivisionError()
        exc2 = RuntimeError()
        b.set_result(1)
        c.set_exception(exc)
        a.set_result(3)
        self._run_loop(self.one_loop)
        self.assertFalse(fut.done())
        d.set_exception(exc2)
        self._run_loop(self.one_loop)
        self.assertTrue(fut.done())
        cb.assert_called_once_with(fut)
        self.assertEqual(fut.result(), [3, 1, exc, exc2])
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_one_cancellation(self):
        a, b, c, d, e = [asyncio.Future(loop=self.one_loop) for i in range(5)]
        fut = asyncio.gather(a, b, c, d, e)
        cb = test_utils.MockCallback()
        fut.add_done_callback(cb)
        a.set_result(1)
        b.cancel()
        self._run_loop(self.one_loop)
        self.assertTrue(fut.done())
        cb.assert_called_once_with(fut)
        self.assertFalse(fut.cancelled())
        self.assertIsInstance(fut.exception(), asyncio.CancelledError)
        # Does nothing
        c.set_result(3)
        d.cancel()
        e.set_exception(RuntimeError())
        e.exception()
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_result_exception_one_cancellation(self):
        a, b, c, d, e, f = [asyncio.Future(loop=self.one_loop)
                            for i in range(6)]
        fut = asyncio.gather(a, b, c, d, e, f, return_exceptions=True)
        cb = test_utils.MockCallback()
        fut.add_done_callback(cb)
        a.set_result(1)
        zde = ZeroDivisionError()
        b.set_exception(zde)
        c.cancel()
        self._run_loop(self.one_loop)
        self.assertFalse(fut.done())
        d.set_result(3)
        e.cancel()
        rte = RuntimeError()
        f.set_exception(rte)
        res = self.one_loop.run_until_complete(fut)
        self.assertIsInstance(res[2], asyncio.CancelledError)
        self.assertIsInstance(res[4], asyncio.CancelledError)
        res[2] = res[4] = None
        self.assertEqual(res, [1, zde, None, 3, None, rte])
        cb.assert_called_once_with(fut)
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_exception_marking(self):
        # Test for the first line marked "Mark exception retrieved."

        @asyncio.coroutine
        def inner(f):
            yield from f
            raise RuntimeError('should not be ignored')

        a = asyncio.Future(loop=self.one_loop)
        b = asyncio.Future(loop=self.one_loop)

        @asyncio.coroutine
        def outer():
            yield from asyncio.gather(inner(a), inner(b), loop=self.one_loop)

        f = asyncio.async(outer(), loop=self.one_loop)
        test_utils.run_briefly(self.one_loop)
        a.set_result(None)
        test_utils.run_briefly(self.one_loop)
        b.set_result(None)
        test_utils.run_briefly(self.one_loop)
        self.assertIsInstance(f.exception(), RuntimeError)
项目:peony-twitter    作者:odrling    | 项目源码 | 文件源码
def test_request_proxy(dummy_client):
    class RaiseProxy:

        def __init__(self, *args, proxy=None, **kwargs):
            raise RuntimeError(proxy)

    async with aiohttp.ClientSession() as session:
        with patch.object(session, 'request', side_effect=RaiseProxy):
            try:
                await dummy_client.request(method='get',
                                           url="http://hello.com",
                                           proxy="http://some.proxy.com",
                                           session=session,
                                           future=asyncio.Future())
            except RuntimeError as e:
                assert str(e) == "http://some.proxy.com"
项目:aiomongo    作者:ZeoAlliance    | 项目源码 | 文件源码
def perform_operation(self, operation) -> bytes:
        request_id = None

        # Because pymongo uses rand() function internally to generate request_id
        # there is a possibility that we have more than one in-flight request with
        # the same id. To avoid this we rerun get_message function that regenerates
        # query with new request id. In most cases this loop will run only once.
        while request_id is None or request_id in self.__request_futures:
            msg = operation.get_message(self.slave_ok, self.is_mongos, True)
            request_id, data, _ = self._split_message(msg)

        response_future = asyncio.Future(loop=self.loop)
        self.__request_futures[request_id] = response_future

        self.send_message(data)

        return await response_future
项目:aiossdb    作者:Microndgt    | 项目源码 | 文件源码
def __init__(self, reader, writer, *, address, encoding=None, parser=None, loop=None):
        if loop is None:
            # ????asyncio?????
            loop = asyncio.get_event_loop()
        if parser is None:
            parser = SSDBParser
        assert callable(parser), "Parser argument: {} is not callable".format(parser)
        self._reader = reader
        self._writer = writer
        self._address = address
        self._loop = loop
        # ???????????????????????popleft
        self._waiters = deque()
        self._parser = parser(encoding=encoding)
        # ?????task, self._read_data()????????????????????
        # ensure_future ??????????????????Future???????????????Task??
        self._reader_task = asyncio.ensure_future(self._read_data(), loop=self._loop)
        # ??????????????????????????????????)
        self._close_waiter = asyncio.Future(loop=self._loop)
        # ?????????(?????)?????
        self._reader_task.add_done_callback(self._close_waiter.set_result)
        self._encoding = encoding

        self._closing = False
        self._closed = False
项目:aiossdb    作者:Microndgt    | 项目源码 | 文件源码
def execute(self, command, *args, encoding=_NOTSET):
        '''??ssdb???????????'''
        if self._reader is None or self._reader.at_eof():
            raise ConnectionClosedError("Connection closed or corrupted")
        if command is None:
            raise TypeError("Command must not be None")
        if None in args:
            raise TypeError("args must not contain None")
        # ??????
        command = command.lower().strip()

        if encoding is _NOTSET:
            encoding = self._encoding
        future = asyncio.Future(loop=self._loop)
        # ????????????????
        self._writer.write(encode_command(command, *args))
        # ?future???????????????????future
        self._waiters.append((future, encoding, command))
        return future
项目:aiofcm    作者:Fatal1ty    | 项目源码 | 文件源码
def send_message(self, message):
        msg = aioxmpp.Message(
            type_=aioxmpp.MessageType.NORMAL
        )
        payload = FCMMessage()

        payload_body = message.as_dict()

        payload.text = json.dumps(payload_body)
        msg.fcm_payload = payload

        future_response = asyncio.Future()
        self.requests[message.message_id] = future_response

        self.refresh_inactivity_timer()
        try:
            await self.xmpp_client.stream.send(msg)
        except:
            self.requests.pop(message.message_id)
            raise

        response = await future_response
        return response
项目:aio-pika    作者:mosquito    | 项目源码 | 文件源码
def delete(self, *, if_unused=True, if_empty=True, timeout=None) -> asyncio.Future:
        """ Delete the queue.

        :param if_unused: Perform delete only when unused
        :param if_empty: Perform delete only when empty
        :param timeout: execution timeout
        :return: :class:`None`
        """

        log.info("Deleting %r", self)

        self._futures.reject_all(RuntimeError("Queue was deleted"))

        future = self._create_future(timeout)

        self._channel.queue_delete(
            future.set_result,
            self.name,
            if_unused=if_unused,
            if_empty=if_empty
        )

        return future
项目:aio-pika    作者:mosquito    | 项目源码 | 文件源码
def _on_connection_lost(self, future: asyncio.Future, connection: AsyncioConnection, code, reason):
        for callback in self._on_connection_lost_callbacks:
            callback(self)

        if self._closed:
            return super()._on_connection_lost(future, connection, code, reason)

        if isinstance(reason, ProbableAuthenticationError):
            if not future.done():
                future.set_exception(reason)

            self.loop.create_task(self.close())

            return

        if not future.done():
            future.set_result(None)

        self.loop.call_later(
            self.reconnect_interval,
            lambda: self.loop.create_task(self.connect())
        )
项目:aio-pika    作者:mosquito    | 项目源码 | 文件源码
def _on_connection_lost(self, future: asyncio.Future, connection: AsyncioConnection, code, reason):
        if self.__closing and self.__closing.done():
            return

        if code == REPLY_SUCCESS:
            return self.__closing.set_result(reason)

        if isinstance(reason, Exception):
            exc = reason
        else:
            exc = ConnectionError(reason, code)

        self.future_store.reject_all(exc)

        if future.done():
            return

        future.set_exception(exc)
项目:PyPlanet    作者:PyPlanet    | 项目源码 | 文件源码
def execute(self):
        """
        Execute call.

        :return: Future with results.
        :rtype: Future<any>
        """
        return await self._client.execute(self.method, *self.args, timeout=self.timeout)
项目:PyPlanet    作者:PyPlanet    | 项目源码 | 文件源码
def execute(self, method, *args, timeout=45.0):
        """
        Query the dedicated server and return the results. This method is a coroutine and should be awaited on.
        The result you get will be a tuple with data inside (the response payload).

        :param method: Server method.
        :param args: Arguments.
        :param timeout: Wait for x seconds until future is returned. Default is 45 seconds.
        :type method: str
        :type args: any
        :return: Tuple with response data (after awaiting).
        :rtype: Future<tuple>
        """
        request_bytes = dumps(args, methodname=method, allow_none=True).encode()
        length_bytes = len(request_bytes).to_bytes(4, byteorder='little')
        handler = self.get_next_handler()

        handler_bytes = handler.to_bytes(4, byteorder='little')

        # Create new future to be returned.
        self.handlers[handler] = future = asyncio.Future()

        # Send to server.
        self.writer.write(length_bytes + handler_bytes + request_bytes)

        return await asyncio.wait_for(future, timeout)
项目:PyPlanet    作者:PyPlanet    | 项目源码 | 文件源码
def __init__(
        self, message, size='md', buttons=None, manager=None, target=None, **data
    ):
        """
        Create an AlertView instance.

        :param message: The message to display to the end-user, Use ``\\n`` for new lines. You can use symbols from FontAwesome
                        by using Unicode escaped strings.
        :param size: Size to use, this parameter should be a string, and one of the following choices:
                     'sm', 'md' or 'lg. Defaults to 'md'.
        :param buttons: Buttons to display, Should be an array with dictionary which contain: name.
        :param manager: UI Manager to use, You should always keep this undefined unless you know what your doing!
        :param target: Target coroutine method called as handle of button clicks.

        :type message: str
        :type title: str
        :type size: str
        :type buttons: list
        :type manager: pyplanet.core.ui._BaseUIManager
        """
        from pyplanet.core import Controller

        super().__init__(manager or Controller.instance.ui_manager)
        self.disable_alt_menu = True
        sizes = self.SIZES[size]

        if not buttons:
            buttons = [{'name': 'OK'}]

        self.target = target
        self.response_future = asyncio.Future()

        self.data = dict(
            message=message,
            buttons=buttons,
            sizes=sizes,
        )
        self.data.update(data)
项目:pyppeteer    作者:miyakogi    | 项目源码 | 文件源码
def clearTimeout(fut: Optional[Union[asyncio.Future, asyncio.Handle]]) -> None:
    """Cancel timer task."""
    if fut:
        fut.cancel()
项目:pyppeteer    作者:miyakogi    | 项目源码 | 文件源码
def __init__(self, connection: Connection, targetId: str, sessionId: str
                 ) -> None:
        """Make new session."""
        super().__init__()
        self._lastId = 0
        self._callbacks: Dict[int, asyncio.Future] = {}
        self._connection: Optional[Connection] = connection
        self._targetId = targetId
        self._sessionId = sessionId
项目:CEX.IO-Client-Python3.5    作者:cexioltd    | 项目源码 | 文件源码
def test_isawaitable(self):

        class SyncCall:
            def method(self):
                pass

            async def async_method(self):
                pass

            def __call__(self, *args):
                pass

        def func():
            pass

        class AsyncCall:
            async def __call__(self, *args):
                pass

        async def coro():
            pass

        @asyncio.coroutine
        def gen_coro():
            pass

        @staticmethod
        def static_method():
            pass

        self.assertFalse(CallChain.is_awaitable(1))
        self.assertFalse(CallChain.is_awaitable(func))
        self.assertTrue(CallChain.is_awaitable(coro))
        self.assertTrue(CallChain.is_awaitable(asyncio.Future()))
        self.assertFalse(CallChain.is_awaitable(static_method))
        self.assertFalse(CallChain.is_awaitable(SyncCall().method))
        self.assertTrue(CallChain.is_awaitable(SyncCall().async_method))
        self.assertFalse(CallChain.is_awaitable(SyncCall()))
        self.assertTrue(CallChain.is_awaitable(AsyncCall()))
        self.assertTrue(CallChain.is_awaitable(gen_coro))
项目:aiosubdomainBrute    作者:OOsec    | 项目源码 | 文件源码
def _callback(fut, domain, result, errorno):
        # type: (asyncio.Future, Any, int) -> None
        if fut.cancelled():
            return
        if errorno is not None:
            fut.set_exception(DNSError(errorno, pycares.errno.strerror(errorno)))
        else:
            if result[0].host != wildcard_dns_record:
                domain_ip = [r.host for r in result]
                result = DomainInfo(domain = domain, ip = domain_ip)
                print(result)
                fut.set_result(result)
            else:
                fut.set_result(None)
项目:aiosubdomainBrute    作者:OOsec    | 项目源码 | 文件源码
def query(self, host, qtype):
        # type: (str, str) -> asyncio.Future
        try:
            qtype = query_type_map[qtype]
        except KeyError:
            raise ValueError('invalid query type: {}'.format(qtype))
        fut = asyncio.Future(loop=self.loop)
        cb = functools.partial(self._callback, fut, host)
        self._channel.query(host, qtype, cb)
        return fut