一个应用服务器,想要提供短链接和长连接两类服务类型时,一般短链接用 HTTP 方式,而长链接采用 WebSocket 方式。

所以用 Flask 如何提供这两种服务类型呢?

这里使用 Flask-uWSGI-WebSocket 这个插件,采用 Nginx + uWSGI + Flask + WebSocket 的方式来提供 HTTP 和 WebSocket 两种服务类型。

  1. 安装 Flask-uWSGI-WebSocket 插件;

    sudo pip3 install Flask-uWSGI-WebSocket
    
  2. 修改 uwsgi 配置文件:

    [uwsgi]
    socket = 127.0.0.1:5051
    master = true
    project = /data/projects/flaskr/
    pythonpath = %(project)
    module = app
    wsgi-file = %(project)/app.py
    callable = app
    processes = 1
    threads = 1
    daemonize = %(project)/server.log
    stats = %(project)/uwsgi/uwsgi.status
    pidfile = %(project)/uwsgi/uwsgi.pid
    
    # 增加
    gevent = 100
    
  3. 修改 Flask 相关逻辑;

    # -*- coding: utf-8 -*-
    __author__ = "winking324@gmail.com"
    __copyright__ = "Copyright (c) 2019 winking.io, Inc."
    
    
    from flask import Flask
    from flask_uwsgi_websocket import GeventWebSocket
    
    
    app = Flask(__name__, instance_relative_config=True)
    websocket = GeventWebSocket(app)
    
    
    @app.route('/')
    def hello_world():
        return 'Hello World!'
    
      
    @websocket.route('/echo')
    def echo(ws):
        while True:
            msg = ws.receive()
            if msg is not None:
                if msg:
                    ws.send(msg)
            else:
                return
    
                  
    if __name__ == '__main__':
        app.run()
    
  4. 重启 uwsgi;

    uwsgi --reload /data/projects/flaskr/uwsgi/uwsgi.pid
    
  5. 测试 WebSocket 服务;