Flask框架(七)uwsgi配置websocket

彭洲
2023-12-01

本文介绍Flask里面uwsgi配置使用websocket功能

1、创建websocket

from flask_uwsgi_websocket import WebSocket

app = create_app(DevelopConfig)
try:
    sockets = WebSocket(app)
except Exception as e:
    logging.error("Error: flask_uwsgi_websocket, {0}".format(e))

注意:uwsgi创建websocket与flask不同:

  • uwsgi:sockets = WebSocket(app)
  • flask:sockets = Sockets(app)

2、创建websocket接口

@sockets.route('/echo')
def echo_socket(ws):
    key = str(ws).split(' ')[-1].rstrip('>')  # 用作服务器给web端推送的标识
    if key not in ws_dict:
        ws_dict[key] = {'ws': ws, 'message': [{'msg': '测试推送服务端推送websocket消息'+key}]}

    while ws.connected:
        message = ws.receive()  # 接收到消息
        if message is not None:
            sendmsg = ws_dict.get(key, {}).get('message')
            if sendmsg:  # 消息不为空时推送
                ws.send(json.dumps(sendmsg[0], ensure_ascii=False))  # 主动给客户端推送消息
                ws_dict[key]['message'] = []

注意:uwsgi获取websocket状态与flask不同:

  • uwsgi:ws.connected
  • flask:ws.closed

3、配置uwsgi启动参数

uwsgi有两种启动方式:命令启动和配置文件启动
命令启动

uwsgi --http-socket :5000 --http-websockets --wsgi-file runserver.py --callable app --master --processes 4 --threads 2

配置文件启动
创建配置文件uwsgi.ini,文件内容如下:

[uwsgi]
 
# uwsgi 启动时所使用的地址与端口
socket = 127.0.0.1:6001
 
# python 调用的模块
module = runserver
 
# python 启动程序文件
wsgi-file = /home/FlaskDemo/runserver.py
 
# python app
callable = app
 
# 处理器数
processes = 4
 
# 线程数
threads = 2

# 设置url地址最大长度, 默认长度是4096
buffer-size = 40960

http-websockets = 1
gevent = 1000
async = 30
 
# 守护进程
daemonize = /home/FlaskDemo/logs/server.log
log-maxsize = 10485760
 类似资料: