Flask框架(七)uwsgi配置websocket

本文介绍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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值