Skip to main content
 首页 » 编程设计

python之Flask-SocketIO 不能在 Apache/WSGI 上工作

2024年10月25日29Renyi-Fan

我使用了来自 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有一个关于在 gevent 模式下运行的部分,但是 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 的东西。