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

标签 python apache flask gevent-socketio flask-socketio

我使用了来自 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 的东西。

关于python - Flask-SocketIO 不能在 Apache/WSGI 上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29921671/

相关文章:

python - xpath 正则表达式不会在 lxml.etree 中搜索 tail

php - 如何在 Ubuntu 15 上的 Apache 服务器上配置虚拟主机

php - .htaccess。拒绝 root,允许特定的子文件夹。可能的?

java - HTTP 状态 500 错误实例化 servlet 类

android - 使用Retrofit将音频文件上传到Flask API

python - Flask 装饰器怎么会有参数?

python - 使用openCV将透明图像叠加到另一个图像上

python - adsdb 插入

python - 使用 python csv 模块创建安装 bash 脚本

python - flask 中的中间件