Django之dwebsocket部署

Django之dwebsocket部署

前言

最近项目中要用到websocket,找了两dwebsocktdjango-redis-websocketdwebsocket使用简单,但是在客户端断开或者连接时,没有信号或者相关处理机制。
django-redis-websocket 通过redis的发布订阅完成websocket的收发,功能较多,但不知何原因部署失败。后来找到了另外一个库WebsockteServer,与django无关,需要另开一个线程处理,用起来还不错。

正式开始

提前准备好一个可用的Django项目,将视图函数与URL匹配好,在debug模式下测试websocket项目是否工作正常


from dwebsocket import accept_websocket

@accept_websocket
def echo(request):
    data = {}
    while True:
        # ...
        if request.is_websocket():
            request.websocket.send(str(json.dumps(data)))
        sleep(5)

1、配置uwsgi
项目以dj_project命名

[uwsgi]
plugins       = python
master        = true
wsgi-file     = /path/to/dj_project/dj_project/wsgi.py
home          = /path/to/venv
chdir         = /path/to/dj_project
socket        = /path/to/dj_project/wst.sock
buffer-size   = 8192
enable-threads= true
close-on-exec = true
vacuum        = true
chmod-socket  = 664
processes     = 2
static-map    = /static/=/path/to/dj_project/static
daemonize     = /path/to/dj_project/wst.log

2、配置nginx

server {
    listen 8000;
    server_name 106.14.13.150;
    root /path/to/dj_project;

   # http
    location / {
        include uwsgi_params;
        uwsgi_read_timeout 3600;
        uwsgi_pass unix:///path/tot/dj_project/wst.sock;
    }

    # websocket
    location /ws/ {
        include uwsgi_params;
        uwsgi_pass unix:///path/to/dj_project/wst.sock;
        #uwsgi_pass http://127.0.0.1:8003;

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

3、使用uwsgi需要在settings.py中加入以下语句

WEBSOCKET_FACTORY_CLASS = 'dwebsocket.backends.uwsgi.factory.uWsgiWebSocketFactory

出现的问题

连接websocket时,nginx error.log提示KeyError: u’REQUEST_METHOD’,需要在location中include uwsgi_params

http://www.h5w3.com/?p=831

猜你喜欢

转载自blog.csdn.net/soga238/article/details/81369908
今日推荐