Python uvloop.install() Examples

The following are 15 code examples of uvloop.install(). 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 uvloop , or try the search function .
Example #1
Source File: server.py    From backend.ai-manager with GNU Lesser General Public License v3.0 5 votes vote down vote up
def main(ctx: click.Context, config_path: Path, debug: bool) -> None:

    cfg = load_config(config_path, debug)
    multiprocessing.set_start_method('spawn')

    if ctx.invoked_subcommand is None:
        cfg['manager']['pid-file'].write_text(str(os.getpid()))
        log_sockpath = Path(f'/tmp/backend.ai/ipc/manager-logger-{os.getpid()}.sock')
        log_sockpath.parent.mkdir(parents=True, exist_ok=True)
        log_endpoint = f'ipc://{log_sockpath}'
        try:
            logger = Logger(cfg['logging'], is_master=True, log_endpoint=log_endpoint)
            with logger:
                ns = cfg['etcd']['namespace']
                setproctitle(f"backend.ai: manager {ns}")
                log.info('Backend.AI Gateway {0}', __version__)
                log.info('runtime: {0}', env_info())
                log_config = logging.getLogger('ai.backend.gateway.config')
                log_config.debug('debug mode enabled.')

                if cfg['manager']['event-loop'] == 'uvloop':
                    import uvloop
                    uvloop.install()
                    log.info('Using uvloop as the event loop backend')
                try:
                    aiotools.start_server(server_main_logwrapper,
                                          num_workers=cfg['manager']['num-proc'],
                                          args=(cfg, log_endpoint))
                finally:
                    log.info('terminated.')
        finally:
            if cfg['manager']['pid-file'].is_file():
                # check is_file() to prevent deleting /dev/null!
                cfg['manager']['pid-file'].unlink()
    else:
        # Click is going to invoke a subcommand.
        pass 
Example #2
Source File: anyio_monkeypatch.py    From purerpc with Apache License 2.0 5 votes vote down vote up
def _new_run(func, *args, backend=None, backend_options=None):
    if backend is None:
        backend = os.getenv("PURERPC_BACKEND", "asyncio")
    log.info("Selected {} backend".format(backend))
    if backend == "uvloop":
        import uvloop
        uvloop.install()
        backend = "asyncio"
    return _anyio_run(func, *args, backend=backend, backend_options=backend_options) 
Example #3
Source File: start.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def execute(argv: Sequence[str] = None):
    """Entrypoint."""
    parser = ArgumentParser()
    parser.prog += " start"
    get_settings = init_argument_parser(parser)
    args = parser.parse_args(argv)
    settings = get_settings(args)
    common_config(settings)

    # set ledger to read only if explicitely specified
    settings["ledger.read_only"] = settings.get("read_only_ledger", False)

    # Support WEBHOOK_URL environment variable
    webhook_url = os.environ.get("WEBHOOK_URL")
    if webhook_url:
        webhook_urls = list(settings.get("admin.webhook_urls") or [])
        webhook_urls.append(webhook_url)
        settings["admin.webhook_urls"] = webhook_urls

    # Create the Conductor instance
    context_builder = DefaultContextBuilder(settings)
    conductor = Conductor(context_builder)

    # Run the application
    if uvloop:
        uvloop.install()
        print("uvloop installed")
    run_loop(start_app(conductor), shutdown_app(conductor)) 
Example #4
Source File: test_asyncio.py    From ton_client with Mozilla Public License 2.0 5 votes vote down vote up
def setUp(self):
        uvloop.install() 
Example #5
Source File: bench.py    From grpclib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def serve_grpclib_uvloop():
    import uvloop
    uvloop.install()

    asyncio.run(_grpclib_server()) 
Example #6
Source File: bench.py    From grpclib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def serve_grpcio_uvloop():
    import uvloop
    uvloop.install()

    from _reference.server import serve

    try:
        asyncio.run(serve())
    except KeyboardInterrupt:
        pass 
Example #7
Source File: bench.py    From grpclib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def serve_aiohttp_uvloop():
    import uvloop
    uvloop.install()

    _aiohttp_server() 
Example #8
Source File: __main__.py    From create-aio-app with MIT License 5 votes vote down vote up
def main() -> None:
    app = init_app()
    app_settings = app['config']['app']

    {%- if cookiecutter.use_uvloop == 'y' %}
    uvloop.install()
    {%- endif %}
    web.run_app(
        app,
        host=app_settings['host'],
        port=app_settings['port'],
    ) 
Example #9
Source File: bot.py    From modmail with GNU Affero General Public License v3.0 5 votes vote down vote up
def main():
    try:
        # noinspection PyUnresolvedReferences
        import uvloop

        logger.debug("Setting up with uvloop.")
        uvloop.install()
    except ImportError:
        pass

    bot = ModmailBot()
    bot.run() 
Example #10
Source File: start_timelord.py    From chia-blockchain with Apache License 2.0 5 votes vote down vote up
def main():
    if uvloop is not None:
        uvloop.install()
    asyncio.run(async_main()) 
Example #11
Source File: start_service.py    From chia-blockchain with Apache License 2.0 5 votes vote down vote up
def run_service(*args, **kwargs):
    if uvloop is not None:
        uvloop.install()
    # TODO: use asyncio.run instead
    # for now, we use `run_until_complete` as `asyncio.run` blocks on RPC server not exiting
    if 1:
        return asyncio.get_event_loop().run_until_complete(
            async_run_service(*args, **kwargs)
        )
    else:
        return asyncio.run(async_run_service(*args, **kwargs)) 
Example #12
Source File: start_wallet.py    From chia-blockchain with Apache License 2.0 5 votes vote down vote up
def main():
    if uvloop is not None:
        uvloop.install()
    asyncio.run(start_websocket_server()) 
Example #13
Source File: app.py    From aioshadowsocks with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, debug=False):
        self.debug = debug
        if not self.debug:
            uvloop.install()

        self.loop = asyncio.get_event_loop()
        self._prepare()
        self.proxyman = ProxyMan(self.listen_host) 
Example #14
Source File: main.py    From proxy_py with GNU General Public License v3.0 5 votes vote down vote up
def init_uvloop():
    import uvloop
    uvloop.install() 
Example #15
Source File: launch.py    From pyrobud with MIT License 5 votes vote down vote up
def setup_asyncio(config: util.config.Config) -> asyncio.AbstractEventLoop:
    """Returns a new asyncio event loop with settings from the given config."""

    asyncio_config: util.config.AsyncIOConfig = config["asyncio"]

    if sys.platform == "win32":
        # Force ProactorEventLoop on Windows for subprocess support
        policy = asyncio.WindowsProactorEventLoopPolicy()
        asyncio.set_event_loop_policy(policy)
    elif not asyncio_config["disable_uvloop"]:
        # Initialize uvloop if available
        try:
            # noinspection PyUnresolvedReferences
            import uvloop

            uvloop.install()
            log.info("Using uvloop event loop")
        except ImportError:
            pass

    loop = asyncio.new_event_loop()

    if asyncio_config["debug"]:
        log.info("Enabling asyncio debug mode")
        loop.set_debug(True)

    return loop