How to use the uvloop.new_event_loop function in uvloop

To help you get started, we’ve selected a few uvloop 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 minhtuan221 / Microservices-connector / tests / example04 / spawn.py View on Github external
except RuntimeError:
            pass
        else:
            if event_loop.is_running():
                raise RuntimeError(
                    "You cannot use AsyncToSync in the same thread as an async event loop - "
                    "just await the async function directly."
                )
        # Make a future for the return information
        call_result = Future()
        # Use call_soon_threadsafe to schedule a synchronous callback on the
        # main event loop's thread
        if not (self.main_event_loop and self.main_event_loop.is_running()):
            # Make our own event loop and run inside that.
            if self.uvloop:
                loop = uvloop.new_event_loop()
            else:
                loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            try:
                loop.run_until_complete(
                    self.main_wrap(args, kwargs, call_result))
            finally:
                try:
                    if hasattr(loop, "shutdown_asyncgens"):
                        loop.run_until_complete(loop.shutdown_asyncgens())
                finally:
                    loop.close()
                    asyncio.set_event_loop(self.main_event_loop)
        else:
            self.main_event_loop.call_soon_threadsafe(
                self.main_event_loop.create_task,
github choleraehyq / aiorpc / tests / test_rpc.py View on Github external
def set_up_inet_server():
    global loop, inet_server
    if not loop:
        loop = uvloop.new_event_loop()
        asyncio.set_event_loop(loop)
    coro = asyncio.start_server(serve, HOST, PORT)
    inet_server = loop.run_until_complete(coro)
github brmmm3 / fastthreadpool / examples / benchmarks / echoserver.py View on Github external
addr[1] = int(addr[1])
        addr = tuple(addr)

    print('serving on: {}'.format(addr))

    if args.pool:
        print(f"creating thread pool with {args.threads} threads")
        print(f"buffer size is {args.bufsize} bytes")
        pool = fastthreadpool.Pool(args.threads)
        pool.submit(pool_echo_server, addr, unix, args.threads, args.bufsize)
        pool.join()
        sys.exit(0)

    if args.uvloop:
        import uvloop
        loop = uvloop.new_event_loop()
        print('using uvloop')
    else:
        loop = asyncio.new_event_loop()
        print('using asyncio loop')

    asyncio.set_event_loop(loop)
    loop.set_debug(False)

    if args.print:
        PRINT = 1

    if hasattr(loop, 'print_debug_info'):
        loop.create_task(print_debug(loop))
        PRINT = 0

    if args.streams:
github aio-libs / aiomonitor / examples / web_srv.py View on Github external
await resp.prepare(request)
    await asyncio.sleep(100, loop=loop)
    resp.write(answer)
    await resp.write_eof()
    return resp


async def init(loop):
    app = web.Application(loop=loop)
    app.router.add_get('/simple', simple)
    app.router.add_get('/hello/{name}', hello)
    app.router.add_get('/hello', hello)
    return app

host, port = 'localhost', 8090
loop = uvloop.new_event_loop()
asyncio.set_event_loop(loop)
app = loop.run_until_complete(init(loop))

with aiomonitor.start_monitor(loop, locals=locals()):
    web.run_app(app, port=port, host=host)
github dabeaz / curio / examples / bench / subproc_perf.py View on Github external
def uvloop_test(n):
    try:
        import uvloop
    except ImportError:
        return

    async def main(n):
        for x in range(n):
            proc = await asyncio.create_subprocess_exec(*cmd, 
                                                        stdin=asyncio.subprocess.PIPE, 
                                                        stdout=asyncio.subprocess.PIPE)
            stdout, stderr = await proc.communicate(input=input)
            await proc.wait()
        assert stdout == input

    loop = uvloop.new_event_loop()
    asyncio.set_event_loop(loop)
    start = time.time()
    loop.run_until_complete(asyncio.ensure_future(main(n)))
    end = time.time()
    print('uvloop:', end-start)
github huge-success / sanic / examples / log_request_id.py View on Github external
@app.middleware('request')
async def set_request_id(request):
    request_id = request.headers.get('X-Request-ID') or str(uuid.uuid4())
    context.set("X-Request-ID", request_id)


@app.route("/")
async def test(request):
    log.debug('X-Request-ID: %s', context.get('X-Request-ID'))
    log.info('Hello from test!')
    return response.json({"test": True})


if __name__ == '__main__':
    asyncio.set_event_loop(uvloop.new_event_loop())
    server = app.create_server(host="0.0.0.0", port=8000, return_asyncio_server=True)
    loop = asyncio.get_event_loop()
    loop.set_task_factory(context.task_factory)
    task = asyncio.ensure_future(server)
    try:
        loop.run_forever()
    except:
        loop.stop()
github vapor-ware / synse-server / synse_server / __main__.py View on Github external
def main() -> None:
    uvloop.install()
    asyncio.set_event_loop(uvloop.new_event_loop())

    parser = argparse.ArgumentParser(
        description='API server for the Synse platform',
    )
    parser.add_argument(
        '--host', required=False, default='0.0.0.0', type=str,
        help='the host/ip for the server to listen on',
    )
    parser.add_argument(
        '--port', required=False, default=5000, type=int,
        help='the port for the server to listen on',
    )
    parser.add_argument(
        '--version', required=False, action='store_true',
        help='print the version',
    )
github choleraehyq / aiorpc / examples / client.py View on Github external
from aiorpc import RPCClient

import asyncio
import uvloop

async def do(cli):
    ret = await client.call('echo', 'message')
    print("{}\n".format(ret))

loop = uvloop.new_event_loop()
asyncio.set_event_loop(loop)
client = RPCClient('127.0.0.1', 6000)
loop.run_until_complete(do(client))
client.close()
github minhtuan221 / Microservices-connector / microservices_connector / minisocket.py View on Github external
def server(self, host='127.0.0.1', port=8765):
        print("Starting socket in %s:%s" % (host, port))
        loop = uvloop.new_event_loop()
        asyncio.set_event_loop(loop)
        start_server = websockets.serve(self.connect, host, port)
        loop.run_until_complete(start_server)
        loop.run_forever()
github iheartradio / Henson / henson / base.py View on Github external
If `uvloop `_ is installed, its event
    loop will be used. Otherwise, the default event loop provided by
    asyncio will be used. The latter behavior can be overridden by
    setting the event loop policy.

    Returns:
        asyncio.AbstractEventLoopPolicy: The new event loop.

    """
    try:
        import uvloop
    except ImportError:
        return asyncio.new_event_loop()
    else:
        return uvloop.new_event_loop()