Websockets and response middleware

Hello!
In a normal http request/response flow there is request/response middlewares,
but for websocket connections works only first - “request”, and the second is not called.
Is there any way to handle when websocket connection closes?
For example - to create DB session in request middleware and close it in “response” like for typical get/post… operations.

So, i had to write custom decorator for WS endpoint to correctly open/close DB session.
Without usage of middleware for this case.

There is no real “response” per se so the response middeware does not really make sense.

What you could do (and is usually the easiest) is something like this:

@app.websocket("/")
async def handler(request, ws):
    try:
        # logic here
        ...
    finally:
        # cleanup here
        ...