启动 script mode 的server,监听可用端口,并自动打开浏览器 Start the server for script mode, and automatically open the browser when the server port is available. PYWEBIO_SCRIPT_MODE_PORT环境变量可以设置监听端口,并关闭自动打开浏览器,用于测试 The PYWEBIO_SCRIPT_MODE_PORT environment variable can set the listening port, just used in
()
| 303 | |
| 304 | |
| 305 | def start_server_in_current_thread_session(): |
| 306 | """启动 script mode 的server,监听可用端口,并自动打开浏览器 |
| 307 | Start the server for script mode, and automatically open the browser when the server port is available. |
| 308 | |
| 309 | PYWEBIO_SCRIPT_MODE_PORT环境变量可以设置监听端口,并关闭自动打开浏览器,用于测试 |
| 310 | The PYWEBIO_SCRIPT_MODE_PORT environment variable can set the listening port, just used in testing. |
| 311 | """ |
| 312 | websocket_conn_opened = threading.Event() |
| 313 | thread = threading.current_thread() |
| 314 | |
| 315 | class SingleSessionWSHandler(_webio_handler(cdn=False)): |
| 316 | session: ScriptModeSession = None |
| 317 | instance: typing.ClassVar = None |
| 318 | closed = False |
| 319 | |
| 320 | def send_msg_to_client(self, session): |
| 321 | for msg in session.get_task_commands(): |
| 322 | try: |
| 323 | self.write_message(json.dumps(msg)) |
| 324 | except TypeError as e: |
| 325 | logger.exception('Data serialization error: %s\n' |
| 326 | 'This may be because you pass the wrong type of parameter to the function' |
| 327 | ' of PyWebIO.\nData content: %s', e, msg) |
| 328 | |
| 329 | def open(self): |
| 330 | if SingleSessionWSHandler.session is None: |
| 331 | SingleSessionWSHandler.instance = self |
| 332 | session_info = get_session_info_from_headers(self.request.headers) |
| 333 | session_info['user_ip'] = self.request.remote_ip |
| 334 | session_info['request'] = self.request |
| 335 | session_info['backend'] = 'tornado' |
| 336 | session_info['protocol'] = 'websocket' |
| 337 | self.session = SingleSessionWSHandler.session = ScriptModeSession( |
| 338 | thread, session_info=session_info, |
| 339 | on_task_command=self.send_msg_to_client, |
| 340 | loop=asyncio.get_event_loop()) |
| 341 | websocket_conn_opened.set() |
| 342 | else: |
| 343 | self.close() |
| 344 | |
| 345 | def on_message(self, data): |
| 346 | if isinstance(data, bytes): |
| 347 | event = deserialize_binary_event(data) |
| 348 | else: |
| 349 | event = json.loads(data) |
| 350 | if event is None: |
| 351 | return |
| 352 | self.session.send_client_event(event) |
| 353 | |
| 354 | def on_close(self): |
| 355 | if self.session is not None: |
| 356 | self.session.close() |
| 357 | self.closed = True |
| 358 | logger.debug('ScriptModeSession closed') |
| 359 | |
| 360 | async def wait_to_stop_loop(server): |
| 361 | """当只剩当前线程和Daemon线程运行时,关闭Server |
| 362 | When only the current thread and Daemon thread are running, close the Server""" |
no outgoing calls
no test coverage detected
searching dependent graphs…