Python, asyncio, and systemd

Chris Angelico rosuav at gmail.com
Tue Jan 17 13:03:04 EST 2017


On Wed, Jan 18, 2017 at 4:06 AM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
>> What's the official way to say to asyncio "here's a listening socket,
>> start managing it for me"?
>
> I haven't tried this but create_server takes a "sock" keyword-argument.
>
> https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.AbstractEventLoop.create_server

Oh. Wow.

I am blind, or an idiot. That is exactly what I'm looking for.

My code now looks like this:

    if sock:
        srv = await loop.create_server(app.make_handler(), sock=sock)
    else:
        srv = await loop.create_server(app.make_handler(), "0.0.0.0", port)
        sock = srv.sockets[0]
    print("Listening on %s:%s" % sock.getsockname(), file=sys.stderr)

According to the docs, host and port must be unset (None) if sock is
given. It'd be nice if they could simply be ignored, in which case I
could just pass in all three parameters. (Yes, I'm forcing this to
IPv4 for this app, rather than using None or "::" to accept IPv6 as
well. If you're copying this code into your app, you should probably
accept IPv6, unless you know otherwise.)

But wow, I just completely didn't see that. I am incredible.

Thank you Ian!

ChrisA



More information about the Python-list mailing list