Unlike django's recommended channel, dwebsocket is much easier and simpler to use.
Usage 1:
Simply add the decorator to the corresponding view function in the file
accept_websocket-—acceptablewebsocketRequests and generalhttprequesting require_websocket----Accept onlywebsocketrequesting,Rejecting the Ordinaryhttprequesting from import accept_websocket,require_websocket @accept_websocket def test_websocket(request): if request.is_websocket(): while 1: (1) ## Send time to front end dit = { 'time':('%Y.%m.%d %H:%M:%S',(())) } ((dit))
Usage 2:
Using middleware
Steps:
1. In the document, add the following information.
import dwebsocket # Provide websockets for all URLs, can be unchecked if only needed for individual views MIDDLEWARE_CLASSES=[''] WEBSOCKET_ACCEPT_ALL=True # Can allow each individual view to utilize websockets
Official Note: After doing the above configuration, websockets will still be denied for normal views, so you have to set the 'accept_websocket ' ' attribute on the view to allow websockets, so continue to do the following configuration.
2. In the document, decorators are added to the relevant views.
from import accept_websocket,require_websocket
@accept_websocket def test_websocket(request): if request.is_websocket(): while 1: (1) ## Send time to front end dit = { 'time':('%Y.%m.%d %H:%M:%S',(())) } ((dit))
It doesn't look much different from method 1, there is one more step of settings configuration, but what's the difference?
It's official.:These attributes are always available if you use the middleware
Translated, this means that if middleware is used, the following methods are available.
request.is_websocket() True for #websocket requests, False for normal requests. # websocket establish a connection, request will have websocket provides the relevant api attributes, if no connection is established then None () # Blocking incoming messages () # Non-blocking reception of messages WebSocket.count_messages() # Returns the number of messages in the queue WebSocket.has_messages() # Returns True if there is a message, and False if there is not. (message) # Send a message WebSocket.__iter__() # When iterators are used
official link
Above this Django through dwebsocket to realize the websocket example is all that I share with you, I hope to give you a reference, and I hope you support me more.