-
In the
I've spent the afternoon looking with no luck, are there any good examples of doing this? An initial attempt with something like this:
fails while negotiating the connection because of a state change in the WebSocket class to If I hack around and bypass the receive by inspecting headers for |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
You should call the Example: from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.routing import WebSocketRoute
from starlette.types import ASGIApp, Message, Receive, Scope, Send
from starlette.websockets import WebSocket
class WSMiddleware:
def __init__(self, app: ASGIApp) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "websocket":
return await self.app(scope, receive, send)
async def wrapped_receive() -> Message:
message = await receive()
print(message)
return message
await self.app(scope, wrapped_receive, send)
async def ws_endpoint(websocket: WebSocket) -> None:
await websocket.accept()
await websocket.send_text("Hello, world!")
await websocket.close()
app = Starlette(
routes=[WebSocketRoute("/", ws_endpoint)],
middleware=[Middleware(WSMiddleware)],
) |
Beta Was this translation helpful? Give feedback.
You should call the
message = await receive()
inside thewrapped_receive
.Example: