|
| 1 | +import socketio |
| 2 | +from fastapi import FastAPI |
| 3 | + |
| 4 | + |
| 5 | +class SocketManager: |
| 6 | + """ |
| 7 | + Integrates SocketIO with FastAPI app. |
| 8 | + Adds `sio` property to FastAPI object (app). |
| 9 | +
|
| 10 | + Default mount location for SocketIO app is at `/ws` |
| 11 | + and defautl SocketIO path is `socket.io`. |
| 12 | + (e.g. full path: `ws://www.example.com/ws/socket.io/) |
| 13 | +
|
| 14 | + SocketManager exposes basic underlying SocketIO functionality |
| 15 | +
|
| 16 | + e.g. emit, on, send, call, etc. |
| 17 | + """ |
| 18 | + |
| 19 | + def __init__( |
| 20 | + self, |
| 21 | + app: FastAPI, |
| 22 | + mount_location: str = "/ws", |
| 23 | + socketio_path: str = "socket.io", |
| 24 | + cors_allowed_origins: list = [], |
| 25 | + ) -> None: |
| 26 | + # TODO: Change Cors policy based on fastapi cors Middleware |
| 27 | + self._sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins="*") |
| 28 | + self._app = socketio.ASGIApp( |
| 29 | + socketio_server=self._sio, socketio_path=socketio_path |
| 30 | + ) |
| 31 | + |
| 32 | + app.mount(mount_location, self._app) |
| 33 | + app.sio = self._sio |
| 34 | + |
| 35 | + def is_asyncio_based(self) -> bool: |
| 36 | + return True |
| 37 | + |
| 38 | + @property |
| 39 | + def on(self): |
| 40 | + return self._sio.on |
| 41 | + |
| 42 | + @property |
| 43 | + def attach(self): |
| 44 | + return self._sio.attach |
| 45 | + |
| 46 | + @property |
| 47 | + def emit(self): |
| 48 | + return self._sio.emit |
| 49 | + |
| 50 | + @property |
| 51 | + def send(self): |
| 52 | + return self._sio.send |
| 53 | + |
| 54 | + @property |
| 55 | + def call(self): |
| 56 | + return self._sio.call |
| 57 | + |
| 58 | + @property |
| 59 | + def close_room(self): |
| 60 | + return self._sio.close_room |
| 61 | + |
| 62 | + @property |
| 63 | + def get_session(self): |
| 64 | + return self._sio.get_session |
| 65 | + |
| 66 | + @property |
| 67 | + def save_session(self): |
| 68 | + return self._sio.save_session |
| 69 | + |
| 70 | + @property |
| 71 | + def session(self): |
| 72 | + return self._sio.session |
| 73 | + |
| 74 | + @property |
| 75 | + def disconnect(self): |
| 76 | + return self._sio.disconnect |
| 77 | + |
| 78 | + @property |
| 79 | + def handle_request(self): |
| 80 | + return self._sio.handle_request |
| 81 | + |
| 82 | + @property |
| 83 | + def start_background_task(self): |
| 84 | + return self._sio.start_background_task |
| 85 | + |
| 86 | + @property |
| 87 | + def sleep(self): |
| 88 | + return self._sio.sleep |
0 commit comments