base.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. import logging
  2. import user_agents
  3. from ..utils import ObjectDict, Setter, catch_exp_call
  4. from collections import defaultdict
  5. logger = logging.getLogger(__name__)
  6. class Session:
  7. """
  8. 会话对象,由Backend创建
  9. 属性:
  10. info 表示会话信息的对象
  11. save 会话的数据对象,提供用户在对象上保存一些会话相关数据
  12. 由Task在当前Session上下文中调用:
  13. get_current_session
  14. get_current_task_id
  15. get_scope_name
  16. pop_scope
  17. push_scope
  18. send_task_command
  19. next_client_event
  20. on_task_exception
  21. register_callback
  22. defer_call
  23. 由Backend调用:
  24. send_client_event
  25. get_task_commands
  26. close
  27. Task和Backend都可调用:
  28. closed
  29. Session是不同的后端Backend与协程交互的桥梁:
  30. 后端Backend在接收到用户浏览器的数据后,会通过调用 ``send_client_event`` 来通知会话,进而由Session驱动协程的运行。
  31. Task内在调用输入输出函数后,会调用 ``send_task_command`` 向会话发送输入输出消息指令, Session将其保存并留给后端Backend处理。
  32. """
  33. @staticmethod
  34. def get_current_session() -> "Session":
  35. raise NotImplementedError
  36. @staticmethod
  37. def get_current_task_id():
  38. raise NotImplementedError
  39. def __init__(self, session_info):
  40. """
  41. :param session_info: 会话信息。可以通过 Session.info 访问
  42. """
  43. self.info = session_info
  44. self.save = Setter()
  45. self.scope_stack = defaultdict(lambda: ['ROOT']) # task_id -> scope栈
  46. self.deferred_functions = [] # 会话结束时运行的函数
  47. self._closed = False
  48. def get_scope_name(self, idx):
  49. """获取当前任务的scope栈检索scope名
  50. :param int idx: scope栈的索引
  51. :return: scope名,不存在时返回 None
  52. """
  53. task_id = type(self).get_current_task_id()
  54. try:
  55. return self.scope_stack[task_id][idx]
  56. except IndexError:
  57. raise ValueError("Scope not found")
  58. def pop_scope(self):
  59. """弹出当前scope
  60. :return: 当前scope名
  61. """
  62. task_id = type(self).get_current_task_id()
  63. try:
  64. return self.scope_stack[task_id].pop()
  65. except IndexError:
  66. raise ValueError("ROOT Scope can't pop")
  67. def push_scope(self, name):
  68. """进入新scope"""
  69. task_id = type(self).get_current_task_id()
  70. self.scope_stack[task_id].append(name)
  71. def send_task_command(self, command):
  72. raise NotImplementedError
  73. def next_client_event(self) -> dict:
  74. """获取来自客户端的下一个事件。阻塞调用,若在等待过程中,会话被用户关闭,则抛出SessionClosedException异常"""
  75. raise NotImplementedError
  76. def send_client_event(self, event):
  77. raise NotImplementedError
  78. def get_task_commands(self) -> list:
  79. raise NotImplementedError
  80. def close(self):
  81. if self._closed:
  82. return
  83. self._closed = True
  84. self.deferred_functions.reverse()
  85. while self.deferred_functions:
  86. func = self.deferred_functions.pop()
  87. catch_exp_call(func, logger)
  88. def closed(self) -> bool:
  89. return self._closed
  90. def on_task_exception(self):
  91. raise NotImplementedError
  92. def register_callback(self, callback, **options):
  93. """ 向Session注册一个回调函数,返回回调id
  94. Session需要保证当收到前端发送的事件消息 ``{event: "callback",task_id: 回调id, data:...}`` 时,
  95. ``callback`` 回调函数被执行, 并传入事件消息中的 ``data`` 字段值作为参数
  96. """
  97. raise NotImplementedError
  98. def defer_call(self, func):
  99. """设置会话结束时调用的函数。可以用于资源清理。
  100. 在会话中可以多次调用 `defer_call()` ,会话结束后将会顺序执行设置的函数。
  101. :param func: 话结束时调用的函数
  102. """
  103. """设置会话结束时调用的函数。可以用于资源清理。"""
  104. self.deferred_functions.append(func)
  105. def get_session_info_from_headers(headers):
  106. """从Http请求头中获取会话信息
  107. :param headers: 字典类型的Http请求头
  108. :return: 表示会话信息的对象,属性有:
  109. * ``user_agent`` : 用户浏览器信息。可用字段见 https://github.com/selwin/python-user-agents#usage
  110. * ``user_language`` : 用户操作系统使用的语言
  111. * ``server_host`` : 当前会话的服务器host,包含域名和端口,端口为80时可以被省略
  112. * ``origin`` : 当前用户的页面地址. 包含 协议、主机、端口 部分. 比如 ``'http://localhost:8080'`` .
  113. 可能为空,但保证当用户的页面地址不在当前服务器下(即 主机、端口部分和 ``server_host`` 不一致)时有值.
  114. """
  115. ua_str = headers.get('User-Agent', '')
  116. ua = user_agents.parse(ua_str)
  117. user_language = headers.get('Accept-Language', '').split(',', 1)[0].split(' ', 1)[0].split(';', 1)[0]
  118. server_host = headers.get('Host', '')
  119. origin = headers.get('Origin', '')
  120. session_info = ObjectDict(user_agent=ua, user_language=user_language,
  121. server_host=server_host, origin=origin)
  122. return session_info