Add websocket.handler.before/after/exception signals.
This commit is contained in:
20
sanic/app.py
20
sanic/app.py
@@ -1369,6 +1369,12 @@ class Sanic(
|
||||
protocol = request.transport.get_protocol()
|
||||
ws = await protocol.websocket_handshake(request, subprotocols)
|
||||
|
||||
await self.dispatch(
|
||||
"websocket.handler.before",
|
||||
inline=True,
|
||||
context={"request": request, "websocket": ws},
|
||||
fail_not_found=False,
|
||||
)
|
||||
# schedule the application handler
|
||||
# its future is kept in self.websocket_tasks in case it
|
||||
# needs to be cancelled due to the server being stopped
|
||||
@@ -1377,10 +1383,24 @@ class Sanic(
|
||||
cancelled = False
|
||||
try:
|
||||
await fut
|
||||
await self.dispatch(
|
||||
"websocket.handler.after",
|
||||
inline=True,
|
||||
context={"request": request, "websocket": ws},
|
||||
reverse=True,
|
||||
fail_not_found=False,
|
||||
)
|
||||
except (CancelledError, ConnectionClosed): # type: ignore
|
||||
cancelled = True
|
||||
except Exception as e:
|
||||
self.error_handler.log(request, e)
|
||||
await self.dispatch(
|
||||
"websocket.handler.exception",
|
||||
inline=True,
|
||||
context={"request": request, "websocket": ws, "exception": e},
|
||||
reverse=True,
|
||||
fail_not_found=False,
|
||||
)
|
||||
finally:
|
||||
self.websocket_tasks.remove(fut)
|
||||
if cancelled:
|
||||
|
||||
@@ -38,6 +38,9 @@ class Event(Enum):
|
||||
HTTP_LIFECYCLE_SEND = "http.lifecycle.send"
|
||||
HTTP_MIDDLEWARE_AFTER = "http.middleware.after"
|
||||
HTTP_MIDDLEWARE_BEFORE = "http.middleware.before"
|
||||
WEBSOCKET_HANDLER_AFTER = "websocket.handler.after"
|
||||
WEBSOCKET_HANDLER_BEFORE = "websocket.handler.before"
|
||||
WEBSOCKET_HANDLER_EXCEPTION = "websocket.handler.exception"
|
||||
|
||||
|
||||
RESERVED_NAMESPACES = {
|
||||
@@ -65,6 +68,11 @@ RESERVED_NAMESPACES = {
|
||||
Event.HTTP_MIDDLEWARE_AFTER.value,
|
||||
Event.HTTP_MIDDLEWARE_BEFORE.value,
|
||||
),
|
||||
"websocket": {
|
||||
Event.WEBSOCKET_HANDLER_AFTER.value,
|
||||
Event.WEBSOCKET_HANDLER_BEFORE.value,
|
||||
Event.WEBSOCKET_HANDLER_EXCEPTION.value,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user