Start the web server. :param port: the port to listen on. Defaults to 8900. The server is started in a background thread.
(self, port=8900)
| 29 | self.thread = None |
| 30 | |
| 31 | def start(self, port=8900): |
| 32 | """Start the web server. |
| 33 | |
| 34 | :param port: the port to listen on. Defaults to 8900. |
| 35 | |
| 36 | The server is started in a background thread. |
| 37 | """ |
| 38 | class ThreadingWSGIServer(ThreadingMixIn, WSGIServer): |
| 39 | pass |
| 40 | |
| 41 | class WebSocketRequestHandler(WSGIRequestHandler): |
| 42 | def get_environ(self): |
| 43 | env = super().get_environ() |
| 44 | |
| 45 | # pass the raw socket to the WSGI app so that it can be used |
| 46 | # by WebSocket connections (hack copied from gunicorn) |
| 47 | env['gunicorn.socket'] = self.connection |
| 48 | return env |
| 49 | |
| 50 | self.httpd = make_server('localhost', port, self._app_wrapper, |
| 51 | ThreadingWSGIServer, WebSocketRequestHandler) |
| 52 | self.thread = threading.Thread(target=self.httpd.serve_forever) |
| 53 | self.thread.start() |
| 54 | |
| 55 | # wait for the server to start |
| 56 | while True: |
| 57 | try: |
| 58 | r = requests.get(f'http://localhost:{port}/') |
| 59 | r.raise_for_status() |
| 60 | if r.text == 'OK': |
| 61 | break |
| 62 | except: |
| 63 | time.sleep(0.1) |
| 64 | |
| 65 | def stop(self): |
| 66 | """Stop the web server.""" |