Django channels, how to turn REST endpoint into websocket endpoint?

I currently have a REST endpoint(GET) to provide some info to clients.
But the client is going to live stream the data as the data source is frequently updated.
The data comes from a device and that device writes data to our backend using REST API endpoints(PUT, POST).

I want to use django channel to turn that GET endpoint into websocket endpoint so the client just need to establish websocket connection once and gets data.

I don’t have any idea how to implement this.
That get method will read data from database and do I need to periodically(let’s say once per second) read data on that socket consumer?
Or can I just send data when the devices call PUT, POST or PATCH methods?
Someone who has rich experience in django channels and websocket can easily answer this question.

Any help would be appreicated.

If you want to see it as a pattern, look at the “Chat Example” as the pattern.

Your client will connect to the “chat server” and will be listening to a “chat room”. The devices will be sending messages in via POST (or PUT). Your endpoint will then be responsible for sending the updated data as a channel message, which will then send it out to all connected clients.

Yes, I understand basic of socket.
But I don’t see any authentication in socket communication.
And I am not sure how I should send data from consumer.
Do I just need to read database every one second and send it to client?
How can I authenticate incoming connections?

That’s because authentication happens before the socket is opened. See Django authentication in the Channels docs.

Yes, that AuthMiddlewareStack does something for authentication I believe.
But anyway, anybody who knows our endpoint can connect to our consumer and get data, right?
I am trying to figure out more thorough way to secure websocket connection

No, that is not correct. Like any other endpoint, you can require an authenticated and authorized user. The docs cover this.
(It looks like Andrew’s multichat example provides a demonstration of requiring authenticated users.)

Yes, I will take a look at that.

Hi @devspectre — also take a look at GitHub - hishnash/djangochannelsrestframework: A Rest-framework for websockets using Django channels-v3 (which is linked from the Channels docs too) — it aims to give you the consumers you need to work with DRF serializers.