python - 开始使用 Django Channels 时遇到问题

标签 python django nginx django-channels daphne

我正在创建自己的应用程序,灵感来自 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/templates/WebSocketTest/Index.html

<script type="text/javascript">
    var dashboard_id = '1';

    var chatSocket = new WebSocket('ws://' + window.location.host +
        '/ws/dboard/' + dashboard_id + '/');

    chatSocket.onmessage = function(e) {
        var data = JSON.parse(e.data);
        console.log(data);
    };

    chatSocket.onclose = function(e) {
        console.error('Chat socket closed unexpectedly');
    };

</script>

WebSocketTest/views.py

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

WebSocketTest/consumers.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/routing.py

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

WebSocketTest/urls.py

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

Dashboard/routing.py

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

Dashboard/urls.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;
  }
}

最佳答案

经过一番搜索,我发现这是 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

关于python - 开始使用 Django Channels 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50808651/

相关文章:

python - 无法使用 SQLAlchemy 删除对象实例

database - django OneToOne 反向访问

amazon-web-services - Nginx 在创建 aws ec2 实例后无法正常工作

javascript - MySql 命令可以从终端运行,但不能从 Node js 运行

amazon-web-services - 将Docker容器部署到AWS时,是否还需要部署自己的反向代理?

python - 使用 Pandas 从具有不同行长度的文件导入数据

python - webapp2 - 只读文件系统错误

python - 我如何告诉我的 ModelAdmin 的过滤器在默认情况下不显示所有记录?

python - Django 中的 Bootstrap 轮播实现

python - MongoDB Python 和 C++ 客户端 - 多个实例出错