Skip to content

Commit

Permalink
Defer constructing startup event until we are definitely in event loop
Browse files Browse the repository at this point in the history
  • Loading branch information
bwhmather committed May 18, 2022
1 parent 5438c06 commit ddccce5
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions uvicorn/server.py
Expand Up @@ -61,9 +61,9 @@ def __init__(

self._main_task: Optional[asyncio.Task] = None

#: Set once immediately after startup has completed and the server has
#: started listening for requests.
self._startup_event = asyncio.Event()
#: Created on demand and set once immediately after startup has
#: completed and the server has started listening for requests.
self._startup_event: Optional[asyncio.Event] = None

def run(self, sockets: Optional[List[socket.socket]] = None) -> None:
self.config.setup_event_loop()
Expand Down Expand Up @@ -100,6 +100,12 @@ async def start_serving(self) -> None:
Idempotent. Can be called multiple times without creating multiple
instances.
"""
if self._startup_event is None:
# We defer creating the startup event until start serving is called
# because there is no guarantee that the constructor will be called
# with an active loop.
self._startup_event = asyncio.Event()

if self._main_task is None:
self._main_task = asyncio.create_task(self._main())

Expand Down

0 comments on commit ddccce5

Please sign in to comment.