How to use sniffio - 10 common examples

To help you get started, we’ve selected a few sniffio examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github bocadilloproject / aiodine / tests / test_aiodine.py View on Github external
async def test_context_manager_dependable_cleanup_on_error() -> None:
    if sniffio.current_async_library() == "curio":
        pytest.xfail(
            "finally' clause with 'await' does not seem to "
            "run correctly on curio (cleaed_up stays False)"
        )

    cleaned_up = False

    @asynccontextmanager
    async def get_connection() -> typing.AsyncIterator[str]:
        nonlocal cleaned_up
        await io()
        try:
            yield "conn"
        finally:
            await io()
            cleaned_up = True
github kyb3r / pycord / pycord / api / gateway.py View on Github external
async def start(self, url):
        """ Start long-term connection with gateway """
        self.alive = True
        url = url + "/" if not url.endswith('/') else url
        url += API.WS_ENDPOINT

        # start connection loop
        self.ws = await asyncwebsockets.create_websocket(url)

        async with anyio.create_task_group() as nursery:
            while self.alive:
                try:
                    if sniffio.current_async_library() == "curio":
                        import curio.meta
                        async with curio.meta.finalize(self.ws):
                            await self.read_data(nursery)
                    else:
                        await self.read_data(nursery)
                except KeyboardInterrupt:
                    await self.close()
                    await self.client.running.set()
                    break
                except Exception as e:
                    await self.client.emit('error', e)
                finally:
                    self.ws.close()
                    self.ws = await asyncwebsockets.create_websocket(url)
github agronholm / anyio / src / anyio / __init__.py View on Github external
Run the given coroutine function in an asynchronous event loop.

    The current thread must not be already running an event loop.

    :param func: a coroutine function
    :param args: positional arguments to ``func``
    :param backend: name of the asynchronous event loop implementation – one of ``asyncio``,
        ``curio`` and ``trio``
    :param backend_options: keyword arguments to call the backend ``run()`` implementation with
    :return: the return value of the coroutine function
    :raises RuntimeError: if an asynchronous event loop is already running in this thread
    :raises LookupError: if the named backend is not found

    """
    try:
        asynclib_name = sniffio.current_async_library()
    except sniffio.AsyncLibraryNotFoundError:
        pass
    else:
        raise RuntimeError(f'Already running {asynclib_name} in this thread')

    try:
        asynclib = import_module(f'{__name__}._backends._{backend}')
    except ImportError as exc:
        raise LookupError(f'No such backend: {backend}') from exc

    token = None
    if sniffio.current_async_library_cvar.get(None) is None:
        # Since we're in control of the event loop, we can cache the name of the async library
        token = sniffio.current_async_library_cvar.set(backend)

    try:
github python-trio / hip / src / ahip / _backends / _loader.py View on Github external
def normalize_backend(backend, async_mode):
    if backend is None:
        if not async_mode:
            backend = Backend(name="sync")
        else:
            import sniffio

            async_library = sniffio.current_async_library()
            if async_library in ("asyncio", "curio"):
                async_library = "anyio"
            backend = Backend(name=async_library)
    elif not isinstance(backend, Backend):
        backend = Backend(name=backend)

    loaders_by_name = backend_directory()
    if backend.name not in loaders_by_name:
        raise ValueError("unknown backend specifier {}".format(backend.name))

    loader = loaders_by_name[backend.name]

    if async_mode and not loader.is_async:
        raise ValueError("{} backend needs to be run in sync mode".format(loader.name))

    if not async_mode and loader.is_async:
github agronholm / anyio / src / anyio / __init__.py View on Github external
def _get_asynclib():
    asynclib_name = sniffio.current_async_library()
    modulename = 'anyio._backends._' + asynclib_name
    try:
        return sys.modules[modulename]
    except KeyError:
        return import_module(modulename)
github florimondmanca / asgi-lifespan / src / asgi_lifespan / _concurrency / __init__.py View on Github external
def detect_concurrency_backend() -> ConcurrencyBackend:
    library = sniffio.current_async_library()

    if library == "asyncio":
        from .asyncio import AsyncioBackend

        return AsyncioBackend()
    elif library == "trio":
        from .trio import TrioBackend

        return TrioBackend()

    raise NotImplementedError(
        f"Unsupported async library: {library}"
    )  # pragma: no cover
github codypiersall / pynng / pynng / _aio.py View on Github external
self.aio = None
        # this is not a public interface, let's make some assertions
        assert isinstance(obj, (pynng.Socket, pynng.Context))
        # we need to choose the correct nng lib functions based on the type of
        # object we've been passed; but really, all the logic is identical
        if isinstance(obj, pynng.Socket):
            self._nng_obj = obj.socket
            self._lib_arecv = lib.nng_recv_aio
            self._lib_asend = lib.nng_send_aio
        else:
            self._nng_obj = obj.context
            self._lib_arecv = lib.nng_ctx_recv
            self._lib_asend = lib.nng_ctx_send
        self.obj = obj
        if async_backend is None:
            async_backend = sniffio.current_async_library()
        if async_backend not in self._aio_helper_map:
            raise ValueError(
                'The async backend {} is not currently supported.'
                .format(async_backend)
            )
        self.awaitable, self.cb_arg = self._aio_helper_map[async_backend](self)
        aio_p = ffi.new('nng_aio **')
        _aio_map[id(self.cb_arg)] = self.cb_arg
        idarg = id(self.cb_arg)
        as_void = ffi.cast('void *', idarg)
        lib.nng_aio_alloc(aio_p, lib._async_complete, as_void)
        self.aio = aio_p[0]
github encode / httpx / httpx / concurrency / auto.py View on Github external
def backend(self) -> ConcurrencyBackend:
        if not hasattr(self, "_backend_implementation"):
            backend = sniffio.current_async_library()
            if backend not in ("asyncio", "trio"):
                raise RuntimeError(f"Unsupported concurrency backend {backend!r}")
            self._backend_implementation = lookup_backend(backend)
        return self._backend_implementation
github kyb3r / pycord / pycord / client.py View on Github external
def __init__(self, library, shard_count=-1, prefixes='py.', message_cache_max=2500, **kwargs):
        super().__init__()
        sniffio.current_async_library_cvar.set(library)
        self.token = ''
        self.is_bot = True
        self._boot_up_time = None
        self.running = anyio.create_event()
        self.api = HttpClient(self)
        self.session = asks.Session()  # public session
        self.shards = [] if shard_count < 1 else list(range(shard_count))
        self.users = Collection(User)
        self.guilds = Collection(Guild)
        self.channels = Collection(Channel)
        self.messages = deque(maxlen=message_cache_max)
        self.commands = CommandCollection(self)
        self.webhooks = Collection(Webhook, indexor='name')
        self.prefixes = prefixes if isinstance(prefixes, list) else [prefixes]
        self._nonces = dict()
        self.user = None
github agronholm / anyio / src / anyio / __init__.py View on Github external
try:
        asynclib_name = sniffio.current_async_library()
    except sniffio.AsyncLibraryNotFoundError:
        pass
    else:
        raise RuntimeError(f'Already running {asynclib_name} in this thread')

    try:
        asynclib = import_module(f'{__name__}._backends._{backend}')
    except ImportError as exc:
        raise LookupError(f'No such backend: {backend}') from exc

    token = None
    if sniffio.current_async_library_cvar.get(None) is None:
        # Since we're in control of the event loop, we can cache the name of the async library
        token = sniffio.current_async_library_cvar.set(backend)

    try:
        backend_options = backend_options or {}
        return asynclib.run(func, *args, **backend_options)  # type: ignore
    finally:
        if token:
            sniffio.current_async_library_cvar.reset(token)

sniffio

Sniff out which async library your code is running under

MIT OR Apache-2.0
Latest version published 3 months ago

Package Health Score

88 / 100
Full package analysis

Similar packages