Skip to content

Add dynamic port binding #10697

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES/10665.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added `port` accessor for dynamic port allocations in `TCPSite` -- by :user:`twhittock-disguise`.
1 change: 1 addition & 0 deletions CONTRIBUTORS.txt
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,7 @@ Thomas Forbes
Thomas Grainger
Tim Menninger
Tolga Tezel
Tom Whittock
Tomasz Trebski
Toshiaki Tanaka
Trinh Hoang Nhu
Expand Down
9 changes: 9 additions & 0 deletions aiohttp/web_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,11 @@ def name(self) -> str:
host = "0.0.0.0" if not self._host else self._host
return str(URL.build(scheme=scheme, host=host, port=self._port))

@property
def port(self) -> int:
"""Return the port number the server is bound to, useful for the dynamically allocated port (0)."""
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please, avoid having the docstring title line exceed 72 chars. You can have a longer paragraph below.
Also, referencing a magic number is not useful to readers unfamiliar with it. Use the ephemeral terminology so people could at least google it. Although, I would probably not even mention it since the underlying implementation details aren't really important to the end-users who'd just use this unconditionally.

return self._port

async def start(self) -> None:
await super().start()
loop = asyncio.get_event_loop()
Expand All @@ -127,6 +132,10 @@ async def start(self) -> None:
reuse_address=self._reuse_address,
reuse_port=self._reuse_port,
)
if self._port == 0:
# Port 0 means bind to any port, so we need to set the attribute
# to the port the server was actually bound to.
self._port = self._server.sockets[0].getsockname()[1]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wouldn't reassign this but track the bound port separately. This is so starting and stopping the TCP site multiple times would be able to get a new port allocated each time.



class UnixSite(BaseSite):
Expand Down
22 changes: 22 additions & 0 deletions docs/web_advanced.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1181,6 +1181,28 @@ the middleware might use :meth:`BaseRequest.clone`.
for modifying *scheme*, *host* and *remote* attributes according
to ``Forwarded`` and ``X-Forwarded-*`` HTTP headers.

Deploying with a dynamic port
-----------------------------

When deploying aiohttp in a zeroconf environment, it may be useful
to have the server bind to a dynamic port. This can be done by
using the ``0`` port number. This will cause the OS to assign a
free port to the server. The assigned port can be retrieved
using the :attr:`TCPSite.port` property after the server has started.

For example::

app = web.Application()
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, 'localhost', 0)
await site.start()

print(f"Server started on port {site.port}")
while True:
await asyncio.sleep(3600) # sleep forever


Swagger support
---------------

Expand Down
Loading