django-channels nginx 设置

django-channels nginx settings

我的 Django 应用程序使用 Django 通道。 我能够使用 gunicorn 和 nginx 将 django 配置为 运行。 应用程序 运行 如果我使用 python manage.py 运行 服务器和 redis 服务器发送通知等,但我无法使用 nginx 配置它。

 server {
    listen 80;
    server_name IP;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/amir/clientcode;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/home/amir/clientcode/adminpanel.sock;
    }
}

然而,当我尝试为 django-channels 配置它时,它给我状态 502

upstream channels-backend {
    server localhost:8000;
}

server {
    listen 80;
    server_name IP;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/amir/clientcode;
    }

    location / {
        try_files $uri @proxy_to_app;
        include proxy_params;
        proxy_pass http://unix:/home/amir/clientcode/adminpanel.sock;
    }

    location @proxy_to_app {
        proxy_pass http://channels-backend;

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Host $server_name;
    }
}

我的 asgi.py 文件

import os
import django
from channels.routing import get_default_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "adminpanel.settings")
django.setup()
application = get_default_application()
``

首先,在您的应用中安装 Daphne: 这里我用daphne==1.3.0

要启动 Daphne 服务器,我使用以下命令:

export DJANGO_SETTINGS_MODULE="config.settings"
exec daphne -b 0.0.0.0 --proxy-headers config.asgi:channel_layer

除了Daphne,你还得开一个worker:

python manage.py runworker

这样,您就可以在同一个 URL 的项目中使用套接字了。

看看这篇文章:https://medium.com/labcodes/introduction-to-django-channels-d1047e56f218

此致