1.下载
pip3 install daphne
pip3 install channels
2.配置
①在settings的INSTALLED_APPS中添加"channels"
②在app下新增consumers.py文件,内容如下:
from channels.generic.websocket import WebsocketConsumer
class NewConsumer(WebsocketConsumer):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 初始化属性
    def connect(self):
        if not self.scope.get("cookies"):
            self.close()
        session_id = self.scope["cookies"].get("sessionid", None)
        if not session_id:
            self.close()
        self.accept()
    def disconnect(self, code):
        self.close()
    def receive(self, text_data=None, bytes_data=None):
        pass
③新增routing.py文件,内容如下:
from django.urls import re_path
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
application = ProtocolTypeRouter({
    # (http->django views is added by default)
    'websocket': AuthMiddlewareStack(
        URLRouter([
            re_path(r'ws/NewConsumer/', NewConsumer),
        ])
    )
})
④新增asgi.py文件,内容如下:
import os
import django
from channels.routing import get_default_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ug_settings.settings")
django.setup()
application = get_default_application()
⑤在settings中添加
ASGI_APPLICATION = 'ug_settings.routing.application'
⑥在supervisor的dj_worker.conf中添加
[program:daphne]
directory=/var/www/html/django/django_app
command=/python3 /var/appvenv/bin/daphne -b 127.0.0.1 -p 8081 --access-log /var/log/daphne.log ug_settings.asgi:application
startsecs=0
stopwaitsecs=10
stopasgroup=true
killasgroup=true
autostart=true
autorestart=true
startretries = 3
startsecs = 5
stdout_logfile_maxbytes = 5MB
stdout_logfile_backups = 5
stdout_logfile=/var/log/daphne/daphne.log
stderr_logfile=/var/log/daphne/daphne_err.log
⑦在nginx的default中添加
location /ws {
    proxy_pass http://127.0.0.1:8081;
    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;
    proxy_read_timeout 3600s;
    add_header 'X-XSS-Protection' '1; mode=block';
    add_header 'Strict-Transport-Security' 'max-age=63072000; includeSubdomains; preload' always;
    add_header 'X-Frame-Options' 'sameorigin' always;
    add_header 'X-Content-Type-Options' 'nosniff';
    add_header 'Content-Security-Policy' "upgrade-insecure-requests;connect-src *";
    add_header 'Access-Control-Allow-Origin' '*';
}

Logo

火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。

更多推荐