我正在尝试运行一个包含网络套接字的烧瓶应用程序,它使用flask_socketio。
我的Python代码如下
from flask import jsonify, request, Flask
from flask_cors import CORS
from flask_socketio import SocketIO
app = Flask(__name__)
socketIo = SocketIO(app, cors_allowed_origins='*', async_mode='gevent')
CORS(app)
data = 5
@socketIo.on('message_emitted')
def handle_message(message):
global data
data = message['value']
# Broadcast the received message to all clients
socketIo.emit('data_changed', { 'value': data })
@app.route('/api/data', methods=['POST'])
def set_data():
global data
data = request.json['value']
socketIo.emit('data_changed', { 'value': data })
return jsonify({'message': 'data is set' })
@app.route('/api/data', methods=['GET'])
def get_data():
return jsonify({'data': { 'value': data } })
@app.route('/')
def home():
return 'Hello for Flask Deployment'
if __name__ == '__main__':
socketIo.run(app=app, debug=True, host='0.0.0.0', port=5000)
当我通过运行命令
gunicorn -w 3 -k gevent server:app
使用gunicorn服务器启动我的应用程序时,出现错误
File ".local/lib/python3.10/site-packages/engineio/async_drivers/gevent.py", line 54, in __call__
raise RuntimeError('The gevent-websocket server is not '
RuntimeError: The gevent-websocket server is not configured appropriately. See the Deployment section of the documentation for more information.
虽然我确实在
async_mode='gevent'
中设置了配置socketIo = SocketIO(app, cors_allowed_origins='*', async_mode='gevent')
,但我也尝试过socketio = SocketIO(app, async_mode='gevent', websocket_class=WebSocketHandler)
。
我检查了文档https://flask-socketio.readthedocs.io/en/latest/deployment.html#:~:text=gunicorn%20%2Dk%20gevent%20%2Dw%201%20module%3Aapp并且我看不出我做错了什么。
我尝试使用命令
gunicorn -w 3 -k gevent server:app
使用gunicorn + gevent 运行我的flask-socketio 应用程序,但出现错误
File ".local/lib/python3.10/site-packages/engineio/async_drivers/gevent.py", line 54, in __call__
raise RuntimeError('The gevent-websocket server is not '
RuntimeError: The gevent-websocket server is not configured appropriately. See the Deployment section of the documentation for more information.
我期望通过添加 async_mode='gevent' ,它应该可以工作。
有人可以帮我用flask-socketio运行gunicorn吗?
提前谢谢您。
我认为你需要在启动时给你的应用程序打补丁。
from gevent import monkey
monkey.patch_all()