Flask-SocketIO 无法在 Apache/WSGI 上工作

Flask-SocketIO Not Working On Apache/WSGI

我使用了 http://blog.miguelgrinberg.com/post/easy-websockets-with-flask-and-gevent/page/4 中的以下示例代码,当我 运行 使用测试服务器时它工作正常,例如python myapp.py 我可以连接到它并发送消息

from flask import Flask, render_template
from flask.ext.socketio import SocketIO, emit

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

@app.route('/')
def index():
    return render_template('index.html')

@socketio.on('my event', namespace='/test')
def test_message(message):
    emit('my response', {'data': message['data']})

@socketio.on('my broadcast event', namespace='/test')
def test_message(message):
    emit('my response', {'data': message['data']}, broadcast=True)

@socketio.on('connect', namespace='/test')
def test_connect():
    emit('my response', {'data': 'Connected'})

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')

if __name__ == '__main__':
    socketio.run(app)

问题是当我将相同的代码移动到使用 Apache 为 Flask 提供服务的服务器时出现错误。

RuntimeError: You need to use a gevent-socketio server.

Apache 主机的配置文件是:

 WSGIApplicationGroup %{GLOBAL}
 WSGIScriptAlias / /var/www/public/flaskApp/flaskApp.wsgi

 <Location /var/www/public/flaskApp/flaskApp/>
    Order allow,deny
    Allow from all
</Location>

是否可以 运行 SocketIO/Flask 并通过 Apache 运行?

您的 /var/www/public/flaskApp/flaskApp.wsgi 文件,Apache 运行 您的应用程序通过该文件不使用支持 socketio 的服务器。

您正在阅读的教程指出

The extension is initialized in the usual way, but to simplify the start up of the server a custom run() method is provided by the extension. This method starts gevent, the only supported web server. Using gunicorn with a gevent worker should also work.

uWSGI documentation has a section on running in gevent mode, but Miguel评论:

uwsgi does not work with this extension either, because it does not allow a custom gevent loop to be used. Gunicorn does work, the command is in the documentation.

所以,Gunicorn。来自 the docs:

An alternative is to use gunicorn as web server, using the worker class provided by gevent-socketio. The command line that starts the server in this way is shown below:

gunicorn --worker-class socketio.sgunicorn.GeventSocketIOWorker module:app

简而言之,确保你是 运行 提供 gevent worker 的东西。