Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask Restful and Flask SocketIO server run together

I'm trying to use Flask Restful and Flask SocketIO at the same time. I already made a Flask Restful application but now I want to use Flask SocketIO to have realtime communication between client and my server.

from flask import Flask
from flask_restful import Api
from flask_socketio import SocketIO

app = Flask(__name__)
api = Api(app)
socketio = SocketIO()

if __name__ == '__main__':
    socketio.run(app, port=5000, host='0.0.0.0')
    app.run(port=5000, host='0.0.0.0')

Once I run this, I get

Traceback (most recent call last):
  File "app.py", line 10, in <module>
    socketio.run(app, port=5000, host='0.0.0.0')
  File "C:\Python27\lib\site-packages\flask_socketio\__init__.py", line 475, in run
    if self.server.eio.async_mode == 'threading':
AttributeError: 'NoneType' object has no attribute 'eio'

I'm a beginner in coding with Flask. Hope you could help me. Thanks.

like image 896
Raniel Christian M. Agno Avatar asked Jan 30 '23 15:01

Raniel Christian M. Agno


1 Answers

Flask-Restful does not change anything with regards to how you start your server. You can do:

app = Flask(__name__)
api = Api(app)
socketio = SocketIO(app)

if __name__ == '__main__':
    socketio.run(app, port=5000, host='0.0.0.0')

The code you pasted in your question had a bug that was causing the AttributeError, and that was that you were not passing the app instance to the SocketIO constructor.

like image 101
Miguel Avatar answered May 08 '23 13:05

Miguel