使用Django Channels開始出現問題

2024-10-02 08:22:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在根据Channels 2.0 tutorial创建自己的应用程序。但是,我无法建立WebSocket连接。Daphne为404投诉说找不到websocket的URL。我不确定错误在哪里。在

更新:我的Daphne在nginx服务器后面运行。nginx配置也会更新:

我的目录结构如下

- SomeDashboardProject
  |-- Dashboard
    |-- asgi.py
    |-- settings.py
    |-- urls.py
    |-- routing.py
    |-- ...
  |-- WebSocketTest
    |-- consumers.py
    |-- routing.py
    |-- urls.py
    |-- views.py
    |-- templates
        |-- WebSocketTest
            |-- index.html

WebSocketTest/模板/WebSocketTest/索引.html

^{pr2}$

WebSocketTest公司/视图.py

def index(request):
    return render(request, 'WebSocketTest/index.html', {})

WebSocketTest公司/消费者.py

class TestConsumer(WebsocketConsumer):

    def connect(self):
        self.accept()

    def disconnect(self, close_code):
        pass

    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        print(message)

WebSocketTest公司/路由.py

websocket_urlpatterns = [
    url(r'^ws/dboard/(?P<dashboard_id>\d+)/$', consumers.TestConsumer),
]

WebSocketTest公司/网址.py

urlpatterns = [
    url(r'^$', views.index, name='index'),
]

仪表板/路由.py

application = ProtocolTypeRouter({
    'websocket': AuthMiddlewareStack(
            URLRouter(
                    WebSocketTest.routing.websocket_urlpatterns
            )
    )
})

仪表板/网址.py

urlpatterns = [
    url(r'^test/', include('websockettest.urls'), name='test'),
]

Daphne错误日志

2018-06-12 02:41:58,857 WARNING  Not Found: /ws/dboard/1/
None - - [12/Jun/2018:02:41:58] "GET /ws/dboard/1/" 404 974

Nginx.conf公司

upstream home {
  server unix:///Users/pranavprakash/workspace/SomeDashboardProject/nginx.sock;
}

# configuration of the server
server {
  # the port your site will be served on
  listen      80;
  # the domain name it will serve for
  server_name localhost; # substitute your machine's IP address or FQDN
  charset     utf-8;

  # max upload size
  client_max_body_size 75M;   # adjust to taste

  # Django media
  location /media  {
    alias /Users/pranavprakash/workspace/SomeDashboardProject/media;
  }

  location /static {
    alias /Users/pranavprakash/workspace/SomeDashboardProject/staticfiles;
  }

  # Finally, send all non-media requests to the Django server.
  location / {
    uwsgi_pass  home;
    include     /Users/pranavprakash/workspace/SomeDashboardProject/uwsgi_params;
  }
}

Tags: textnamepyselfdataindexserverdef
1条回答
网友
1楼 · 发布于 2024-10-02 08:22:16

经过一点搜索,我发现这是Nginx配置的问题。我发布的nginx配置不允许websockets。需要进行以下更改:

location / {
    uwsgi_pass  home;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
    include     /Users/pranavprakash/workspace/SomeDashboardProject/uwsgi_params;
  }

更多详细信息请访问Nginx blog post

相关问题 更多 >

    热门问题