淺談django channels 路由誤導
與django路由有區別
他們都有根路由,但是不一樣。
django的根路由:
urlpatterns = [ path(’login/’,include(’login.urls’)), path(’’,views.home), path(’helloapp/’, include(’helloapp.urls’)), path(’admin/’, admin.site.urls),]
channels的根路由:
只能形如這種樣子,URLRouter里面是一個列表,列表當中是具體路由條目。
application = ProtocolTypeRouter({ # (http->django views is added by default) ’websocket’: AuthMiddlewareStack( URLRouter([ re_path(r’ws/chat/(?P<room_name>w+)/$’, consumers.ChatConsumer), #path(’’, consumers.rtcConsumer),]) ),})
有人說為什么不能這樣呢?
application = ProtocolTypeRouter({ # (http->django views is added by default) ’websocket’: AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ),})
問得好,的確可以,這也是文檔的寫法,替換一下是一樣的。根路由指向chat這個APP的路由條目,而chat.routing.websocket_urlpatterns就等于:
[re_path(r’ws/chat/(?P<room_name>w+)/$’, consumers.ChatConsumer), path(’’, consumers.rtcConsumer),]
那么,假如我有兩個APP(webrtc和chat)需要用到websocket,那么我很自然的想到在兩個APP中分別新建routing.py路由文件,然后將根路由寫成這樣:
application = ProtocolTypeRouter({ # (http->django views is added by default) ’websocket’: AuthMiddlewareStack( URLRouter( webrtc.routing.websocket_urlpatterns, chat.routing.websocket_urlpatterns, ) ),})
很遺憾,報錯參數過多。加個列表:
application = ProtocolTypeRouter({ # (http->django views is added by default) ’websocket’: AuthMiddlewareStack( URLRouter([ webrtc.routing.websocket_urlpatterns, chat.routing.websocket_urlpatterns, ]) ),})
依然錯誤。我甚至將兩個路由的list合成一個list才沒問題:
routinglist=[]routinglist.extend(chat.routing.websocket_urlpatterns)routinglist.extend(webrtc.routing.websocket_urlpatterns)application = ProtocolTypeRouter({ # (http->django views is added by default) ’websocket’: AuthMiddlewareStack( URLRouter( routinglist ) ),})
請問,根路由的作用究竟在哪?這個根路由的作用在于不僅僅只有websocket,還有一些其他的服務,看到上面代碼的逗號就明白了。但是如果只用websocket,這個根路由沒意義,因為它只能指向一個routing.py.
文檔的誤導
文檔讓我們一步一步實現一個簡單的聊天室,他將routing.py寫在chat這個APP的目錄下,如果我除了chat這個APP需要用到websocket,那么其他APP的路由也得寫到chat里面的routing.py。因此,我為什么要將routing.py放在chat里面呢,它又不是chat專屬。
更一般的形式
所以我建議,別學文檔例子,將routing.py文件放在任何APP之下,而應該放在工程目錄下(與APP同目錄)創建一個文件夾如consumer,在里面創建routing.py和消費者。
channels文檔真不細致,怪不得用的人少,網上一點有用的資料沒有
找到文檔的websocket消費者,就這么一點?
而在源碼中有這么多:
def websocket_connect(self, message) def connect(self) def accept(self, subprotocol=None) def websocket_receive(self, message) def receive(self, text_data=None, bytes_data=None) def send(self, text_data=None, bytes_data=None, close=False) def close(self, code=None) def websocket_disconnect(self, message) def disconnect(self, code)
看過一句話
django使用websocket最好的辦法是用tornado做websocket服務器
到此這篇關于淺談django channels 路由誤導的文章就介紹到這了,更多相關django channels 路由內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: