Flask-SocketIO 'Connect' callback

1.1k views Asked by At

I'm trying to access variables that are being passed from the client (iOS; Swift) to the server on a Flask-SocketIO connection on the connect action. Let me explain. When you want to do a random action you have something like this on the server which includes a callback (see data in the code below):

@socketio.on('custom action', namespace = '/mynamespace')
def handle_custom_action(data):
    print data

There are some preset actions (like connect) and apparently connect does not have any callback when it's called so the client cannot send any data on the connect action:

@socketio.on('connect', namespace = '/mynamespace')
def handle_connection(data):
    print data # nothing gets printed

I looked into the code a bit deeper and found this. The definition of the on function is:

def on(self, message, namespace=None):

And then within that function (I'm omitting a bit of code to get to the point):

if message == 'connect':
    ret = handler()
else:
    ret = handler(*args)

I could be wrong but it appears that code explicitly does not return anything back on connect and I'm not sure why? I've found some evidence that this is possible in node.js (I will update this with proper links when I find them) so I'm wondering why this isn't possible in the Flask-SocketIO library or whether I'm just misunderstanding what I'm looking at (and if so, how to get those parameters).

Thanks!


Update: I did find a way to access connection parameters but it doesn't seem like the 'right' way. I'm using the global request and splitting the GET parameters / query string that come through on the request:

data = dict(item.split("=") for item in request.event["args"][0]["QUERY_STRING"].split("&"))

OR as two lines:

data = request.event["args"][0]["QUERY_STRING"].split("&"))
data = dict(item.split("=") for item in data.split("&"))

Flask-SocketIO adds event which connects a dictionary with keys of message and args and within args is the QUERY_STRING which I then split add turn into a dictionary. This works fine but it doesn't necessarily answer the original question as to why there is no callback?


Here is an example of the iOS connection params being passed:

let connectParams = SocketIOClientOption.connectParams(["user_id" : Int(user.userId)!, "connection_id" : self.socketConnectionId])
self.socket = SocketIOClient(socketURL: URL(string: "http://www.myurl.com")!, config: [.nsp("/namespace"), .forceWebsockets(true), .forceNew(true), connectParams])
0

There are 0 answers