Python asyncio.get_running_loop() Examples

The following are 30 code examples of asyncio.get_running_loop(). 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 asyncio , or try the search function .
Example #1
Source File: utils.py    From quart with MIT License 8 votes vote down vote up
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 
Example #2
Source File: utils.py    From lbry-sdk with MIT License 6 votes vote down vote up
def async_timed_cache(duration: int):
    def wrapper(func):
        cache: typing.Dict[typing.Tuple,
                           typing.Tuple[typing.Any, float]] = {}

        @functools.wraps(func)
        async def _inner(*args, **kwargs) -> typing.Any:
            loop = asyncio.get_running_loop()
            time_now = loop.time()
            key = tuple([args, tuple([tuple([k, kwargs[k]]) for k in kwargs])])
            if key in cache and (time_now - cache[key][1] < duration):
                return cache[key][0]
            to_cache = await func(*args, **kwargs)
            cache[key] = to_cache, time_now
            return to_cache
        return _inner
    return wrapper 
Example #3
Source File: Requestable.py    From supriya with MIT License 6 votes vote down vote up
def communicate_async(self, server=None, sync=True, timeout=1.0):
        (
            success_pattern,
            failure_pattern,
            requestable,
        ) = self._get_response_patterns_and_requestable(server)
        if self._handle_async(sync, server):
            return
        loop = asyncio.get_running_loop()
        self._response_future = loop.create_future()
        server.osc_protocol.register(
            pattern=success_pattern,
            failure_pattern=failure_pattern,
            procedure=self._set_response_async,
            once=True,
        )
        server.send(requestable.to_osc())
        await asyncio.wait_for(self._response_future, timeout=timeout)
        return self._response 
Example #4
Source File: 04_pubsub.py    From aioredis with MIT License 6 votes vote down vote up
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() 
Example #5
Source File: taskgroup.py    From edgedb with Apache License 2.0 6 votes vote down vote up
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 
Example #6
Source File: baseheader.py    From torba with MIT License 6 votes vote down vote up
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 
Example #7
Source File: 05_pubsub.py    From aioredis with MIT License 6 votes vote down vote up
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() 
Example #8
Source File: servers.py    From supriya with MIT License 6 votes vote down vote up
def boot(
        self, port=DEFAULT_PORT, *, scsynth_path=None, options=None, **kwargs
    ):
        if self._is_running:
            raise supriya.exceptions.ServerOnline
        port = port or DEFAULT_PORT
        loop = asyncio.get_running_loop()
        self._boot_future = loop.create_future()
        self._quit_future = loop.create_future()
        self._options = new(options or Options(), **kwargs)
        scsynth_path = scsynth.find(scsynth_path)
        self._process_protocol = AsyncProcessProtocol()
        await self._process_protocol.boot(self._options, scsynth_path, port)
        if not await self._process_protocol.boot_future:
            self._boot_future.set_result(False)
            self._quit_future.set_result(True)
            raise supriya.exceptions.ServerCannotBoot
        self._ip_address = "127.0.0.1"
        self._is_owner = True
        self._port = port
        await self._connect()
        return self 
Example #9
Source File: http_client.py    From galaxy_blizzard_plugin with MIT License 6 votes vote down vote up
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 
Example #10
Source File: web.py    From mergify-engine with Apache License 2.0 6 votes vote down vote up
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}
    ) 
Example #11
Source File: file_analysis.py    From lbry-sdk with MIT License 6 votes vote down vote up
def _verify_ffmpeg_installed(self):
        if self._ffmpeg_installed:
            return
        self._ffmpeg_installed = False
        path = self._conf.ffmpeg_path
        if hasattr(self._conf, "data_dir"):
            path += os.path.pathsep + os.path.join(getattr(self._conf, "data_dir"), "ffmpeg", "bin")
        path += os.path.pathsep + self._env_copy.get("PATH", "")
        self._which_ffmpeg, self._which_ffprobe = await asyncio.get_running_loop().run_in_executor(
            None, self._which_ffmpeg_and_ffmprobe, path
        )
        if not self._which_ffmpeg:
            log.warning("Unable to locate ffmpeg executable. Path: %s", path)
            raise FileNotFoundError(f"Unable to locate ffmpeg executable. Path: {path}")
        if not self._which_ffprobe:
            log.warning("Unable to locate ffprobe executable. Path: %s", path)
            raise FileNotFoundError(f"Unable to locate ffprobe executable. Path: {path}")
        if os.path.dirname(self._which_ffmpeg) != os.path.dirname(self._which_ffprobe):
            log.warning("ffmpeg and ffprobe are in different folders!")

        await self._verify_executables()
        self._ffmpeg_installed = True 
Example #12
Source File: websocket.py    From aiounifi with MIT License 6 votes vote down vote up
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 
Example #13
Source File: xmppserver.py    From bumper with GNU General Public License v3.0 6 votes vote down vote up
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()) 
Example #14
Source File: sig.py    From naz with MIT License 6 votes vote down vote up
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),
            },
        ) 
Example #15
Source File: jsonrpc.py    From Galaxy_Plugin_Bethesda with MIT License 6 votes vote down vote up
def send_request(self, method, params, sensitive_params):
        """
        Send request

        :param method:
        :param params:
        :param sensitive_params: list of parameters that are anonymized before logging; \
            if False - no params are considered sensitive, if True - all params are considered sensitive
        """
        self._last_request_id += 1
        request_id = str(self._last_request_id)

        loop = asyncio.get_running_loop()
        future = loop.create_future()
        self._requests_futures[self._last_request_id] = (future, sensitive_params)

        logging.info(
            "Sending request: id=%s, method=%s, params=%s",
            request_id, method, anonymise_sensitive_params(params, sensitive_params)
        )

        self._send_request(request_id, method, params)
        return await future 
Example #16
Source File: wyze_bulb.py    From ha-wyzeapi with Apache License 2.0 6 votes vote down vote up
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 
Example #17
Source File: wyze_switch.py    From ha-wyzeapi with Apache License 2.0 6 votes vote down vote up
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 
Example #18
Source File: websocket_server.py    From chia-blockchain with Apache License 2.0 6 votes vote down vote up
def start(self):
        self.log.info("Starting Websocket 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")

        await self.start_wallet()

        await self.connect_to_daemon()
        self.log.info("webSocketServer closed") 
Example #19
Source File: server.py    From chia-blockchain with Apache License 2.0 6 votes vote down vote up
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") 
Example #20
Source File: blockchain.py    From chia-blockchain with Apache License 2.0 6 votes vote down vote up
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 
Example #21
Source File: adb_manager_async.py    From python-androidtv with MIT License 5 votes vote down vote up
def shell(self, cmd):
        """Send a shell command."""
        return await asyncio.get_running_loop().run_in_executor(None, self._device.shell, cmd)


# pylint: disable=too-few-public-methods 
Example #22
Source File: compat.py    From aiosmtplib with MIT License 5 votes vote down vote up
def get_running_loop() -> asyncio.AbstractEventLoop:
    if PY37_OR_LATER:
        return asyncio.get_running_loop()

    loop = asyncio.get_event_loop()
    if not loop.is_running():
        raise RuntimeError("no running event loop")

    return loop 
Example #23
Source File: protocols.py    From supriya with MIT License 5 votes vote down vote up
def boot(self, options, scsynth_path, port):
        if self.is_running:
            return
        self.is_running = False
        options_string = options.as_options_string(port)
        command = "{} {}".format(scsynth_path, options_string)
        logger.info(command)
        loop = asyncio.get_running_loop()
        self.boot_future = loop.create_future()
        self.exit_future = loop.create_future()
        _, _ = await loop.subprocess_exec(
            lambda: self, *command.split(), stdin=None, stderr=None
        ) 
Example #24
Source File: __init__.py    From aiocqhttp with MIT License 5 votes vote down vote up
def _before_serving(self):
        self._loop = asyncio.get_running_loop() 
Example #25
Source File: core.py    From aioshadowsocks with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.loop = asyncio.get_running_loop()
        self.timeout_handle = self.loop.call_later(self.TIMEOUT, self._timeout)

        self._need_clean = False 
Example #26
Source File: controller.py    From ansible-api with GNU General Public License v3.0 5 votes vote down vote up
def post(self, request):
        data = request.json if request.json is not None else {}
        for test in ['n', 'm', 't', 's']:  # required parameter check
            if test not in data:
                return json({'error': "Lack of necessary parameters [%s]" % test,
                             'rc': ErrorCode.ERRCODE_BIZ})

        bad_cmd = ['reboot', 'su', 'sudo', 'dd', 'mkfs', 'shutdown', 'half', 'top']
        name = data.get('n').encode('utf-8').decode()
        module = data.get('m')
        arg = data.get('a', '').encode('utf-8').decode()
        target = data.get('t')
        sign = data.get('s')
        # sudo = True if data.get('r') else False # discard
        # forks = data.get('c', 50) # discard
        cmd_info = arg.split(' ', 1)
        Tool.LOGGER.info('run: {0}, {1}, {2}, {3}'.format(
            name, target, module, arg))
        check_str = Tool.encrypt_sign(name, module, target, Config.get('sign_key'))
        if sign != check_str:
            return json({'error': "Sign is error", 'rc': ErrorCode.ERRCODE_BIZ})
        else:
            if module in ('shell', 'command') and cmd_info[0] in bad_cmd:
                return json({'error': "This is danger shell: " + cmd_info[0], 'rc': ErrorCode.ERRCODE_BIZ})
            else:
                try:
                    cb = CallBack()
                    cb.status_drawer(dict(status='starting', raw=lambda: dict(
                        task_name=module, event='playbook_on_play_start', runner_ident=name,
                        event_data=dict(pattern=target, name=module)),
                                          after=lambda: dict(task_list=[module])))
                    loop = asyncio.get_running_loop()
                    with concurrent.futures.ThreadPoolExecutor() as pool:
                        response = await loop.run_in_executor(pool, self.run, target, name, module, arg, cb)
                        return json(dict(rc=response.rc, detail=cb.get_summary()))
                except Exception as e:
                    Tool.LOGGER.exception(e)
                    return json({'error': str(e), 'rc': ErrorCode.ERRCODE_BIZ}) 
Example #27
Source File: poolserver.py    From Zilliqa-Mining-Proxy with GNU General Public License v3.0 5 votes vote down vote up
def start_stratum(config):
    # run stratum server
    port = config["stratum_server"].get("port", "33456")
    host = config["stratum_server"].get("host", "0.0.0.0")

    loop = asyncio.get_running_loop()
    server = await loop.create_server(add_stratum_protocol(), host, port)

    logging.info(f"Stratum server running at: {host}:{port}")

    async with server:
        await server.serve_forever() 
Example #28
Source File: adb_manager_async.py    From python-androidtv with MIT License 5 votes vote down vote up
def pull(self, device_path, local_path):
        """Download a file."""
        return await asyncio.get_running_loop().run_in_executor(None, self._device.pull, device_path, local_path) 
Example #29
Source File: adb_manager_async.py    From python-androidtv with MIT License 5 votes vote down vote up
def push(self, local_path, device_path):
        """Upload a file."""
        return await asyncio.get_running_loop().run_in_executor(None, self._device.push, local_path, device_path) 
Example #30
Source File: protocols.py    From supriya with MIT License 5 votes vote down vote up
def connection_made(self, transport):
        loop = asyncio.get_running_loop()
        self.transport = transport
        self.is_running = True
        if self.healthcheck:
            self.healthcheck_task = loop.create_task(self._run_healthcheck())