Skip to content
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

websocket: ensure handler on_close() is called after open() #2966

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
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
10 changes: 9 additions & 1 deletion tornado/websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,8 @@ def __init__(
self.close_code = None # type: Optional[int]
self.close_reason = None # type: Optional[str]
self.stream = None # type: Optional[IOStream]
self._opening = False
self._need_close = False
self._on_close_called = False

async def get(self, *args: Any, **kwargs: Any) -> None:
Expand Down Expand Up @@ -563,7 +565,9 @@ def on_connection_close(self) -> None:
if self.ws_connection:
self.ws_connection.on_connection_close()
self.ws_connection = None
if not self._on_close_called:
if self._opening:
self._need_close = True
elif not self._on_close_called:
self._on_close_called = True
self.on_close()
self._break_cycles()
Expand Down Expand Up @@ -950,9 +954,13 @@ async def _accept_connection(self, handler: WebSocketHandler) -> None:

self.start_pinging()
try:
handler._opening = True
open_result = handler.open(*handler.open_args, **handler.open_kwargs)
if open_result is not None:
await open_result
handler._opening = False
if handler._need_close:
handler.on_connection_close()
except Exception:
handler.log_exception(*sys.exc_info())
self._abort()
Expand Down