當前位置: 首頁>>代碼示例>>Python>>正文


Python asyncio.get_running_loop方法代碼示例

本文整理匯總了Python中asyncio.get_running_loop方法的典型用法代碼示例。如果您正苦於以下問題:Python asyncio.get_running_loop方法的具體用法?Python asyncio.get_running_loop怎麽用?Python asyncio.get_running_loop使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在asyncio的用法示例。


在下文中一共展示了asyncio.get_running_loop方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: run_sync

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import get_running_loop [as 別名]
def run_sync(func: Callable[..., Any]) -> Callable[..., Coroutine[Any, None, None]]:
    """Ensure that the sync function is run within the event loop.

    If the *func* is not a coroutine it will be wrapped such that
    it runs in the default executor (use loop.set_default_executor
    to change). This ensures that synchronous functions do not
    block the event loop.
    """

    @wraps(func)
    async def _wrapper(*args: Any, **kwargs: Any) -> Any:
        loop = asyncio.get_running_loop()
        result = await loop.run_in_executor(
            None, copy_context().run, partial(func, *args, **kwargs)
        )
        if isgenerator(result):
            return run_sync_iterable(result)  # type: ignore
        else:
            return result

    _wrapper._quart_async_wrapper = True  # type: ignore
    return _wrapper 
開發者ID:pgjones,項目名稱:quart,代碼行數:24,代碼來源:utils.py

示例2: run_sync_iterable

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import get_running_loop [as 別名]
def run_sync_iterable(iterable: Generator[Any, None, None]) -> AsyncGenerator[Any, None]:
    async def _gen_wrapper() -> AsyncGenerator[Any, None]:
        # Wrap the generator such that each iteration runs
        # in the executor. Then rationalise the raised
        # errors so that it ends.
        def _inner() -> Any:
            # https://bugs.python.org/issue26221
            # StopIteration errors are swallowed by the
            # run_in_exector method
            try:
                return next(iterable)
            except StopIteration:
                raise StopAsyncIteration()

        loop = asyncio.get_running_loop()
        while True:
            try:
                yield await loop.run_in_executor(None, copy_context().run, _inner)
            except StopAsyncIteration:
                return

    return _gen_wrapper() 
開發者ID:pgjones,項目名稱:quart,代碼行數:24,代碼來源:utils.py

示例3: main

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import get_running_loop [as 別名]
def main():
    redis = await aioredis.create_redis_pool('redis://localhost')

    ch, = await redis.psubscribe('channel:*')
    assert isinstance(ch, aioredis.Channel)

    async def reader(channel):
        async for ch, message in channel.iter():
            print("Got message in channel:", ch, ":", message)
    asyncio.get_running_loop().create_task(reader(ch))

    await redis.publish('channel:1', 'Hello')
    await redis.publish('channel:2', 'World')

    redis.close()
    await redis.wait_closed() 
開發者ID:aio-libs,項目名稱:aioredis,代碼行數:18,代碼來源:05_pubsub.py

示例4: main

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import get_running_loop [as 別名]
def main():
    redis = await aioredis.create_redis_pool('redis://localhost')

    ch1, ch2 = await redis.subscribe('channel:1', 'channel:2')
    assert isinstance(ch1, aioredis.Channel)
    assert isinstance(ch2, aioredis.Channel)

    async def reader(channel):
        async for message in channel.iter():
            print("Got message:", message)
    asyncio.get_running_loop().create_task(reader(ch1))
    asyncio.get_running_loop().create_task(reader(ch2))

    await redis.publish('channel:1', 'Hello')
    await redis.publish('channel:2', 'World')

    redis.close()
    await redis.wait_closed() 
開發者ID:aio-libs,項目名稱:aioredis,代碼行數:20,代碼來源:04_pubsub.py

示例5: __aenter__

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import get_running_loop [as 別名]
def __aenter__(self):
        if self._entered:
            raise RuntimeError(
                f"TaskGroup {self!r} has been already entered")
        self._entered = True

        if self._loop is None:
            self._loop = asyncio.get_running_loop()

        self._parent_task = asyncio.current_task(self._loop)
        if self._parent_task is None:
            raise RuntimeError(
                f'TaskGroup {self!r} cannot determine the parent task')
        self._patch_task(self._parent_task)

        return self 
開發者ID:edgedb,項目名稱:edgedb,代碼行數:18,代碼來源:taskgroup.py

示例6: connect

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import get_running_loop [as 別名]
def connect(self, start: int, headers: bytes) -> int:
        added = 0
        bail = False
        loop = asyncio.get_running_loop()
        async with self._header_connect_lock:
            for height, chunk in self._iterate_chunks(start, headers):
                try:
                    # validate_chunk() is CPU bound and reads previous chunks from file system
                    await loop.run_in_executor(None, self.validate_chunk, height, chunk)
                except InvalidHeader as e:
                    bail = True
                    chunk = chunk[:(height-e.height)*self.header_size]
                written = 0
                if chunk:
                    self.io.seek(height * self.header_size, os.SEEK_SET)
                    written = self.io.write(chunk) // self.header_size
                    self.io.truncate()
                    # .seek()/.write()/.truncate() might also .flush() when needed
                    # the goal here is mainly to ensure we're definitely flush()'ing
                    await loop.run_in_executor(None, self.io.flush)
                    self._size = None
                added += written
                if bail:
                    break
        return added 
開發者ID:lbryio,項目名稱:torba,代碼行數:27,代碼來源:baseheader.py

示例7: get_auth_data_login

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import get_running_loop [as 別名]
def get_auth_data_login(self, cookie_jar, credentials):
        code = parse_qs(urlparse(credentials['end_uri']).query)["code"][0]
        loop = asyncio.get_running_loop()

        s = requests.Session()
        url = f"{self.blizzard_oauth_url}/token"
        data = {
            "grant_type": "authorization_code",
            "redirect_uri": REDIRECT_URI,
            "client_id": CLIENT_ID,
            "client_secret": CLIENT_SECRET,
            "code": code
        }
        response = await loop.run_in_executor(None, partial(s.post, url, data=data))
        response.raise_for_status()
        result = response.json()
        access_token = result["access_token"]
        self.auth_data = WebsiteAuthData(cookie_jar=cookie_jar, access_token=access_token, region=self.region)
        return self.auth_data

    # NOTE: use user data to present usertag/name to Galaxy, if this token expires and plugin cannot refresh it
    # use stored usertag/name if token validation fails, this is temporary solution, as we do not need that
    # endpoint for nothing else at this moment 
開發者ID:bartok765,項目名稱:galaxy_blizzard_plugin,代碼行數:25,代碼來源:http_client.py

示例8: simulator

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import get_running_loop [as 別名]
def simulator(request: requests.Request):
    token = request.headers.get("Authorization")
    if token:
        token = token[6:]  # Drop 'token '

    data = SimulatorSchema(await request.json())
    if data["pull_request"]:
        loop = asyncio.get_running_loop()
        title, summary = await loop.run_in_executor(
            None,
            functools.partial(
                _sync_simulator,
                data["mergify.yml"]["pull_request_rules"],
                *data["pull_request"],
                token=token,
            ),
        )
    else:
        title, summary = ("The configuration is valid", None)

    return responses.JSONResponse(
        status_code=200, content={"title": title, "summary": summary}
    ) 
開發者ID:Mergifyio,項目名稱:mergify-engine,代碼行數:25,代碼來源:web.py

示例9: __init__

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import get_running_loop [as 別名]
def __init__(
        self, session, host, port, ssl_context, site, callback, is_unifi_os=False,
    ):
        """Create resources for websocket communication."""
        self.session = session
        self.ssl_context = ssl_context
        self.session_handler_callback = callback

        if is_unifi_os:
            self.url = f"wss://{host}:{port}/proxy/network/wss/s/{site}/events"
        else:
            self.url = f"wss://{host}:{port}/wss/s/{site}/events"

        self._loop = asyncio.get_running_loop()

        self._data = None
        self._state = None 
開發者ID:Kane610,項目名稱:aiounifi,代碼行數:19,代碼來源:websocket.py

示例10: start_async_server

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import get_running_loop [as 別名]
def start_async_server(self):
        try:
            xmppserverlog.info(
                "Starting XMPP Server at {}:{}".format(self.address[0], self.address[1])
            )

            loop = asyncio.get_running_loop()

            self.server = await loop.create_server(
                self.xmpp_protocol, host=self.address[0], port=self.address[1]
            )

            self.server_coro = loop.create_task(self.server.serve_forever())

        except PermissionError as e:
            xmppserverlog.error(e.strerror)
            asyncio.create_task(bumper.shutdown())
            pass

        except asyncio.CancelledError:
            pass

        except Exception as e:
            xmppserverlog.exception("{}".format(e))
            asyncio.create_task(bumper.shutdown()) 
開發者ID:bmartin5692,項目名稱:bumper,代碼行數:27,代碼來源:xmppserver.py

示例11: _signal_handling

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import get_running_loop [as 別名]
def _signal_handling(logger: logging.Logger, client: naz.Client) -> None:
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError:
        loop = asyncio.get_event_loop()

    try:
        for _signal in [signal.SIGHUP, signal.SIGQUIT, signal.SIGTERM]:
            loop.add_signal_handler(
                _signal,
                functools.partial(
                    asyncio.ensure_future,
                    _handle_termination_signal(logger=logger, _signal=_signal, client=client),
                ),
            )
    except ValueError as e:
        logger.log(
            logging.DEBUG,
            {
                "event": "naz.cli.signals",
                "stage": "end",
                "state": "this OS does not support the said signal",
                "error": str(e),
            },
        ) 
開發者ID:komuw,項目名稱:naz,代碼行數:27,代碼來源:sig.py

示例12: async_turn_off

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import get_running_loop [as 別名]
def async_turn_off(self):
        _LOGGER.debug("Light " + self._friendly_name + " turning off.")
        url = 'https://api.wyzecam.com/app/v2/device/set_property'

        payload = {
            'phone_id': self._api._device_id,
            'access_token': self._api._access_token,
            'device_model': self._device_model,
            'ts': '1575948896791',
            'sc': '01dd431d098546f9baf5233724fa2ee2',
            'sv': '107693eb44244a948901572ddab807eb',
            'device_mac': self._device_mac,
            'pvalue': "0",
            'pid': 'P3',
            'app_ver': 'com.hualai.WyzeCam___2.6.62'
        }

        loop = asyncio.get_running_loop()
        loop.create_task(self._api.async_do_request(url, payload))

        self._state = False
        self._just_changed_state = True 
開發者ID:JoshuaMulliken,項目名稱:ha-wyzeapi,代碼行數:24,代碼來源:wyze_bulb.py

示例13: async_turn_on

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import get_running_loop [as 別名]
def async_turn_on(self):
        _LOGGER.debug("Switch " + self._friendly_name + " turning on.")
        url = 'https://api.wyzecam.com/app/v2/device/set_property'

        payload = {
            'phone_id': self._api._device_id,
            'access_token': self._api._access_token,
            'device_model': self._device_model,
            'ts': '1575948896791',
            'sc': '01dd431d098546f9baf5233724fa2ee2',
            'sv': '107693eb44244a948901572ddab807eb',
            'device_mac': self._device_mac,
            'pvalue': "1",
            'pid': 'P3',
            'app_ver': 'com.hualai.WyzeCam___2.6.62'
        }

        loop = asyncio.get_running_loop()
        loop.create_task(self._api.async_do_request(url, payload))

        self._state = True
        self._just_changed_state = True 
開發者ID:JoshuaMulliken,項目名稱:ha-wyzeapi,代碼行數:24,代碼來源:wyze_switch.py

示例14: start

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import get_running_loop [as 別名]
def start(self):
        self.log.info("Starting Daemon Server")

        def master_close_cb():
            asyncio.ensure_future(self.stop())

        try:
            asyncio.get_running_loop().add_signal_handler(
                signal.SIGINT, master_close_cb
            )
            asyncio.get_running_loop().add_signal_handler(
                signal.SIGTERM, master_close_cb
            )
        except NotImplementedError:
            self.log.info("Not implemented")

        self.websocket_server = await websockets.serve(
            self.safe_handle, "localhost", 55400
        )

        self.log.info("Waiting Daemon WebSocketServer closure")
        print("Daemon server started", flush=True)
        await self.websocket_server.wait_closed()
        self.log.info("Daemon WebSocketServer closed") 
開發者ID:Chia-Network,項目名稱:chia-blockchain,代碼行數:26,代碼來源:server.py

示例15: pre_validate_blocks_multiprocessing

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import get_running_loop [as 別名]
def pre_validate_blocks_multiprocessing(
        self, blocks: List[FullBlock]
    ) -> List[Tuple[bool, Optional[bytes32]]]:
        futures = []
        # Pool of workers to validate blocks concurrently
        for block in blocks:
            if self._shut_down:
                return [(False, None) for _ in range(len(blocks))]
            futures.append(
                asyncio.get_running_loop().run_in_executor(
                    self.pool,
                    pre_validate_finished_block_header,
                    self.constants,
                    bytes(block),
                )
            )
        results = await asyncio.gather(*futures)

        for i, (val, pos) in enumerate(results):
            if pos is not None:
                pos = bytes32(pos)
            results[i] = val, pos
        return results 
開發者ID:Chia-Network,項目名稱:chia-blockchain,代碼行數:25,代碼來源:blockchain.py


注:本文中的asyncio.get_running_loop方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。