Gunicorn 中 Django 通道的 WebSocket 连接问题

问题描述 投票:0回答:1

我尝试使用 Django Channels 和 Daphne 实现实时聊天。它在我的本地服务器上运行良好,但现在我想使用 Gunicorn、nginx 在生产中实现它。但是,当我重新加载并重新启动并运行时,我在服务中收到错误(如下图所示)。我尝试修改我的服务,但仍然不起作用。由于没有具体的错误,我无法找出原因。我阅读了一些文档,我是否需要进行迁移?任何想法将不胜感激。

enter image description here

这是我尝试过的

服务Gunicorn

[Unit]
Description=Tris application daemon services
Requires=tev.socket
After=network.target

[Service]
User=dswdcaraga
Group=www-data
WorkingDirectory=/opt/apps/tev
Environment=DJANGO_SETTINGS_MODULE=tev.settings
ExecStart=/opt/apps/env/bin/daphne -u /run/tev/tev.sock tev.asgi:application --bind 0.0.0.0:8000

[Install]
WantedBy=multi-user.target

Nginx

server {
server_name caraga-tris-staging.dswd.gov.ph;
listen 80;
return 301 https://caraga-tris-staging.dswd.gov.ph$request_uri;
}
server {
    server_name caraga-tris-staging.dswd.gov.ph;
    listen 443 ssl;

    #ssl_certificate /etc/ssl/certs/caraga/server-cer.pem;
    #ssl_certificate_key /etc/ssl/certs/caraga/server-key.key;

    ssl_certificate /etc/ssl/certs/caraga/ssl_nginx/server-cer.pem;
    ssl_certificate_key /etc/ssl/certs/caraga/ssl_nginx/server-key.key;


    location / {
        include proxy_params;
        proxy_pass http://unix:/run/tev/tev.sock;

        #WebSocket support
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        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_headers_hash_max_size 1024;
    proxy_headers_hash_bucket_size 128;

asgi.py配置

import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
#from django.core.asgi import get_asgi_application
from channels.auth import AuthMiddlewareStack
from main import routing
import main.routing

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tev.settings')

django.setup()

django_asgi_app = get_asgi_application()

#application = get_asgi_application()
application = ProtocolTypeRouter({
    #"http": get_asgi_application(),
    "http": django_asgi_app,
    "websocket": URLRouter(
        main.routing.websocket_urlpatterns
    )
})
django nginx server gunicorn
1个回答
0
投票

您只需将这些行移到 asgi.py 文件的顶部即可。

import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project.settings")

import django

django.setup()

并且不要忘记将

nginx
服务中的套接字路由到 /ws url:

location /ws/ {
        proxy_pass http://unix:/run/daphne/daphne.sock;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        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-Proto $scheme;
    }
© www.soinside.com 2019 - 2024. All rights reserved.