Flask: RESTful API and SocketIO Server

Background

I am trying to create a simple REST API using the Flask-RESTful extension. This API will work primarily for CRUD management and user authentication for a simple service.

I am also trying to create several web sockets using the Flask-SocketIO extension, with which these users can connect and view real-time updates for some data related to other people using this service. Thus, I need to know that these users are authenticated and authorized to connect to specific sockets.

Problem

However, I had problems with the setup. It seems like I cannot use these two components (REST API and SocketIO server) together in the same Flask instance. The reason I say this is because when I run the following, either a REST API or a SocketIO server will work, but not both:

from flask import Flask from flask_restful import Api from flask.ext.socketio import SocketIO app = Flask(__name__) api = Api(app) socketio = SocketIO(app) # some test resources for the API and # a test emitter statement for the SocketIO server # are added here if __name__ == '__main__': app.run(port=5000) socketio.run(app, port=5005) 

Question

Is a typical solution for this type of installation to have two different Flask instances running at the same time? For example, should my SocketIO server make requests to my REST API to verify that a particular user is authenticated / authorized to connect to a specific socket?

+6
source share
1 answer

You just want to run socketio.run(app, port=5005) and push the REST API on port 5005.

The reason this happens is because under the hood Flask-SocketIO starts a gevent-based web server (or with release 1.0, also an eventlet) - this server processes websocket requests directly (using handlers that you register through socketio.on decorator) and passes requests not related to websocket to Flask.

The reason your code didn't work is because both app.run and socketio.run are blocking operations. Whatever the first launch, it went in cycles, waiting for connections, not allowing the second to start. If you really need to start your network connections on a different port, you will need to call a socket or run application for another process.

+11
source

All Articles