WebSocket with Class-based views?

Does WebSocket support Class-based views?

If so, what is the syntax?

If not, are there any plans to add it?

This is the first I have heard this request. Please feel free to add a ticket as it does make sense to have as a feature.

With that said, you can sort of make something work.

class CBVWebsocket(HTTPMethodView):
    @classmethod
    async def websocket(self, *args, **kwargs):
        print(args)
        print(kwargs)
        _, interface = args
        while True:
            message = await interface.recv()
            try:
                if message:
                    print(message)
                else:
                    print("NO MESSAGE")
                    break
            except Exception:
                print("Exception")
        print("DONE")


app.websocket("/foo")(CBVWebsocket.websocket)

In actuality, there is no reason this needs to be an HTTPMethodView. And, it sort of defeats the purpose because it means you cannot go and register other methods on that path.

But, to answer the question, no it is not really supported.

1 Like

Thanks! The main reason that I tend to prefer method view is because I can inherit classes. Overtime, I’ve found that when there are too many related endpoints that share some functionalities, it’s easier to work with method views that can extend behavior while having the same base class, instead of repeatedly defining module level functions that do things.

My guess is that this is not what it’s intended but personally I do this to make my code more manageable.

1 Like