Skip to content

Inspecting incoming websocket data in middleware #2535

Closed Answered by Kludex
nickolas1 asked this question in Q&A
Discussion options

You must be logged in to vote

You should call the message = await receive() inside the wrapped_receive.

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()
            p…

Replies: 1 comment

Comment options

Kludex
Apr 20, 2024
Maintainer Sponsor

You must be logged in to vote
0 replies
Answer selected by Kludex
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants