django channels 路由 浅谈django channels 路由误导

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

django channels 路由 浅谈django channels 路由误导

我是注释   2021-04-22 我要评论

与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服务器

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们