base.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. class AbstractSession:
  2. """
  3. 会话对象,由Backend创建
  4. 由Task在当前Session上下文中调用:
  5. get_current_session
  6. get_current_task_id
  7. send_task_command
  8. next_client_event
  9. on_task_exception
  10. register_callback
  11. 由Backend调用:
  12. send_client_event
  13. get_task_commands
  14. close
  15. Task和Backend都可调用:
  16. closed
  17. Session是不同的后端Backend与协程交互的桥梁:
  18. 后端Backend在接收到用户浏览器的数据后,会通过调用 ``send_client_event`` 来通知会话,进而由Session驱动协程的运行。
  19. Task内在调用输入输出函数后,会调用 ``send_task_command`` 向会话发送输入输出消息指令, Session将其保存并留给后端Backend处理。
  20. """
  21. @staticmethod
  22. def get_current_session() -> "AbstractSession":
  23. raise NotImplementedError
  24. @staticmethod
  25. def get_current_task_id():
  26. raise NotImplementedError
  27. def __init__(self, target, on_task_command=None, on_session_close=None, **kwargs):
  28. """
  29. :param target:
  30. :param on_task_command: Backend向ession注册的处理函数,当 Session 收到task发送的command时调用
  31. :param on_session_close: Backend向Session注册的处理函数,当 Session task执行结束时调用 *
  32. :param kwargs:
  33. .. note::
  34. 后端Backend在相应on_session_close时关闭连接时,需要保证会话内的所有消息都传送到了客户端
  35. """
  36. raise NotImplementedError
  37. def send_task_command(self, command):
  38. raise NotImplementedError
  39. def next_client_event(self) -> dict:
  40. raise NotImplementedError
  41. def send_client_event(self, event):
  42. raise NotImplementedError
  43. def get_task_commands(self) -> list:
  44. raise NotImplementedError
  45. def close(self):
  46. raise NotImplementedError
  47. def closed(self) -> bool:
  48. raise NotImplementedError
  49. def on_task_exception(self):
  50. raise NotImplementedError
  51. def register_callback(self, callback, **options):
  52. """ 向Session注册一个回调函数,返回回调id
  53. Session需要保证当收到前端发送的事件消息 ``{event: "callback",task_id: 回调id, data:...}`` 时,
  54. ``callback`` 回调函数被执行, 并传入事件消息中的 ``data`` 字段值作为参数
  55. """
  56. raise NotImplementedError