How to run flask socket.io on localhost (xampp)

2.2k views Asked by At

The tutorials I have seen use the following code to run the server:

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

My __init__.py file is:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.orm import sessionmaker
from sqlalchemy import *
from flask.ext.socketio import SocketIO, emit                                                                                       


app = Flask(__name__)
socketio = SocketIO(app)
app.debug = True
engine = create_engine('mysql://root:my_pw@localhost/db_name') 
DBSession = sessionmaker(bind=engine)
import couponmonk.views

My views.py file contains all the @app.route and @socketio decorators.

My question is, where should I be placing the code:

socketio.run(app)

When I put it in the __init__.py_ file, I receive the errors:

File "/opt/lampp/htdocs/flaskapp/flask.wsgi", line 7, in <module>
from couponmonk import app as application
File "/home/giri/Desktop/couponmonk/venv/couponmonk/__init__.py", line 14, in <module>
socketio.run(app)
File "/home/giri/Desktop/couponmonk/venv/lib/python2.7/site-packages/flask_socketio/__init__.py", line 411, in run
run_with_reloader(run_server)
File "/home/giri/Desktop/couponmonk/venv/lib/python2.7/site-packages/werkzeug/serving.py", line 632, in run_with_reloader
return run_with_reloader(*args, **kwargs)
File "/home/giri/Desktop/couponmonk/venv/lib/python2.7/site-packages/werkzeug/_reloader.py", line 231, in run_with_reloader
sys.exit(reloader.restart_with_reloader())
SystemExit: 2
2

There are 2 answers

1
Miguel Grinberg On BEST ANSWER

Author of Flask-SocketIO here.

Unfortunately this extension cannot work with a standard web server, you will not be able to host an app that uses it over apache/mod_wsgi. You need to use a gevent server, and not a generic one, but one that is customized for Socket.IO.

That means that Apache is out (it does not even support WebSocket traffic). Also uWSGI is out (supports gevent, but not possible to use a custom gevent server). As a side note, Python 3 is also currently out, as gevent only runs on Python 2 (though I think there's going to be good news about this soon, I'm working on some ideas to get socketio running on Python 3 right now).

The choices that you have are given in the documentation. Summary:

  • socketio.run(app), which runs the custom socketio gevent server directly.
  • Gunicorn with a custom socketio worker (command line shown in docs)

You can put nginx as reverse proxy in front of your server if you like. The configuration is also shown in the docs.

Good luck!

0
CESCO On

Seems lime you are trying to use Miguel's Flask-socketIO extension, right? It only supports Guinicorn as the WSGI server, and advice you to use NGINX as a proxy pass. I know nothing about xampp but as far as I have read; It's possible to do a proxy pass since one of the latest versions of Apache. Have not tried though.