Uebertreiberman
Uebertreiberman

Reputation: 141

How to separate sockets for logically separated Flask routes?

I have a rather complex Flask project structure set up that uses blueprints to separate different "modules" from one another, and then different routes in each module. I now want to add socket functionalities to this project using the flask-socketio library. My goal is to assign each socket to it's own thread, managed by an object. The problem I am facing now is that I'm unsure how to properly separate the sockets from one another.

(Please note that I am very deep in experimentation phase right now, I don't have a final concept yet and therefore no conclusive code snippets to show)

From my understanding each socket has a unique socket-ID, which is stored in flask.request.sid while the context is within a socketio-event. That is great, because I can use this to match events to the open socket, meaning I know which "disconnect"-event belongs to which "connect"-event, since both have the same socket-ID if they are part of the same socket connection.

Now the problems start though. I am attempting to find a way that based on which route the socket is called from the socket has different event handlers. Meaning the route .../admin/a manages different events than .../admin/b, because both routes lead to different logical parts of my web application. On an even larger scale, I only have one global socketio-object shared over all blueprints of my application. If I add an event handler to react to socket feedback of blueprint 1, I absolutely don't want blueprint 2 to be able to also trigger it with it's own sockets.

What are the recommended ways of handling socket separation? Is that even something that's getting used in practise or do I have a fundamentally wrong understanding of how socket connections should be used in web applications?

Upvotes: 1

Views: 633

Answers (1)

Miguel Grinberg
Miguel Grinberg

Reputation: 67489

If you have different logical groups of socket events that you want to be independent of each other, you can use a different namespace for each. In Socket.IO one or more namespaces can be multiplexed on the same physical transport.

If you prefer something simpler, just avoid conflicts in the name that you assign to your events.

Upvotes: 2

Related Questions