0

I have a flask app that processes a web socket stream of audio from Twilio.

The app works fine without gunicorn but when I start it with gunicorn I get only the first message of the socket (connect) and an unsuccessful handshake. Here is how the app looks:

from flask import Flask
from flask_sockets import Sockets
from geventwebsocket.handler import WebSocketHandler
from gevent import pywsgi
...

app = Flask(__name__)
sockets = Sockets(app)
...
@sockets.route('/media')
def media(ws):
    ...
if __name__ == '__main__':
    server = pywsgi.WSGIServer(('', HTTP_SERVER_PORT), app, handler_class=WebSocketHandler)
    server.serve_forever()

When I start the app directly using python flaskapp.py it works ok.

When I start it using gunicorn by writing:

gunicorn -k flask_sockets.worker --bind 0.0.0.0:5055 --log-level=bug flaskapp:app

this is where the connection "hangs" and carries no further than the initial connection, apparently due to the handshake failing.

It's important to note that I haven't "gevent monkey patched" the code, but I'm not sure if it has anything to do with the problem.

Any idea will much be appreciated!

Leo
  • 900
  • 1
  • 11
  • 26

1 Answers1

0

Don't have the ability to test this right now, but perhaps try with:

from flask import Flask
from flask_sockets import Sockets
from geventwebsocket.handler import WebSocketHandler
from gevent import pywsgi
...

app = Flask(__name__)
sockets = Sockets(app)
...
@sockets.route('/media')
def media(ws):
    ...

server = pywsgi.WSGIServer(('', HTTP_SERVER_PORT), app, handler_class=WebSocketHandler)

if __name__ == '__main__':
    server.serve_forever()

Then change the launch command to:

gunicorn -k flask_sockets.worker --bind 0.0.0.0:5055 --log-level=bug flaskapp:server

(Gunicorn should be importing the server object, which can't live within that final if statement, as that code only runs when launched with python directly).

v25
  • 7,096
  • 2
  • 20
  • 36