Running flask-socketio in thread Running flask-socketio in thread flask flask

Running flask-socketio in thread


Since the question received an upvote, I can mention I solved this conundrum by thinking outside the box. Instead of flask-socketio, I changed to aiohttp.

My solution goes something like this (incomplete code):

from aiohttp import webclass MyThreadedServer(Thread):    def __init__(self):        self._loop = None  # The event loop for the async web server    async def _on_shutdown(self, app):        for conn in set(self.connections):            await conn.close()    def run(self):        #Runs a separate asyncio loop on this (separate) thread        self._loop = asyncio.new_event_loop()        asyncio.set_event_loop(self._loop)        self.stop_server = asyncio.Event()        self._loop.run_until_complete(self._run_app())        #Or in Python 3.7, simply:        #  asyncio.run(run())        self._loop.close()    async def _run_app(self):        self.app = web.Application()        self.app.on_shutdown.append(self._on_shutdown)            runner = web.AppRunner(self.app)        await runner.setup()        site = web.TCPSite(runner, self.hostname, self.port)        await site.start()        print('Started web server on %s port %d' % (self.hostname, self.port))        await self.stop_server.wait()        print('Web server closing down')    def stop(self):        "Call from any thread"        # Overrides EventThread.stop() to change implementation        if self.stop_server:            self._loop.call_soon_threadsafe(self.stop_server.set)