1
0

base.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. import logging
  2. import sys
  3. import traceback
  4. from collections import defaultdict
  5. import user_agents
  6. from ..exceptions import SessionException
  7. logger = logging.getLogger(__name__)
  8. class Session:
  9. """
  10. 会话对象,由Backend创建
  11. 属性:
  12. info 表示会话信息的对象
  13. save 会话的数据对象,提供用户在对象上保存一些会话相关数据
  14. 由Task在当前Session上下文中调用:
  15. get_current_session
  16. get_current_task_id
  17. get_scope_name
  18. pop_scope
  19. push_scope
  20. send_task_command
  21. next_client_event
  22. on_task_exception
  23. register_callback
  24. need_keep_alive
  25. defer_call
  26. 由Backend调用:
  27. send_client_event
  28. get_task_commands
  29. close
  30. Task和Backend都可调用:
  31. closed
  32. Session是不同的后端Backend与协程交互的桥梁:
  33. 后端Backend在接收到用户浏览器的数据后,会通过调用 ``send_client_event`` 来通知会话,进而由Session驱动协程的运行。
  34. Task内在调用输入输出函数后,会调用 ``send_task_command`` 向会话发送输入输出消息指令, Session将其保存并留给后端Backend处理。
  35. """
  36. debug = False
  37. @staticmethod
  38. def get_current_session() -> "Session":
  39. raise NotImplementedError
  40. @staticmethod
  41. def get_current_task_id():
  42. raise NotImplementedError
  43. def __init__(self, session_info):
  44. """
  45. :param session_info: 会话信息。可以通过 Session.info 访问
  46. """
  47. self.internal_save = dict(info=session_info) # some session related info, just for internal used
  48. self.save = {} # underlying implement of `pywebio.session.data`
  49. self.scope_stack = defaultdict(lambda: ['ROOT']) # task_id -> scope栈
  50. self.deferred_functions = [] # 会话结束时运行的函数
  51. self._closed = False
  52. def get_scope_name(self, idx):
  53. """获取当前任务的scope栈检索scope名
  54. :param int idx: scope栈的索引
  55. :return: scope名,不存在时返回 None
  56. """
  57. task_id = type(self).get_current_task_id()
  58. try:
  59. return self.scope_stack[task_id][idx]
  60. except IndexError:
  61. raise ValueError("Scope not found")
  62. def pop_scope(self):
  63. """弹出当前scope
  64. :return: 当前scope名
  65. """
  66. task_id = type(self).get_current_task_id()
  67. try:
  68. return self.scope_stack[task_id].pop()
  69. except IndexError:
  70. raise ValueError("ROOT Scope can't pop") from None
  71. def push_scope(self, name):
  72. """进入新scope"""
  73. task_id = type(self).get_current_task_id()
  74. self.scope_stack[task_id].append(name)
  75. def send_task_command(self, command):
  76. raise NotImplementedError
  77. def next_client_event(self) -> dict:
  78. """获取来自客户端的下一个事件。阻塞调用,若在等待过程中,会话被用户关闭,则抛出SessionClosedException异常"""
  79. raise NotImplementedError
  80. def send_client_event(self, event):
  81. raise NotImplementedError
  82. def get_task_commands(self) -> list:
  83. raise NotImplementedError
  84. def close(self, nonblock=False):
  85. """Close current session
  86. :param bool nonblock: Don't block thread. Used in closing from backend.
  87. """
  88. if self._closed:
  89. return
  90. self._closed = True
  91. self.deferred_functions.reverse()
  92. while self.deferred_functions:
  93. func = self.deferred_functions.pop()
  94. try:
  95. func()
  96. except Exception as e:
  97. msg = "Error occurred when running deferred function %s" % func
  98. if isinstance(e, SessionException):
  99. msg = "PyWebIO interactive functions cannot be called inside the deferred functions."
  100. logger.exception(msg)
  101. def closed(self) -> bool:
  102. return self._closed
  103. def on_task_exception(self):
  104. from ..output import toast, popup, put_error, PopupSize
  105. from . import run_js
  106. from . import info as session_info
  107. # log exception in server
  108. logger.exception('Unhandled error in pywebio app')
  109. try:
  110. toast_msg = "应用发生内部错误" if 'zh' in session_info.user_language else "An internal error occurred in the application"
  111. if type(self).debug:
  112. e_type, e_value, e_tb = sys.exc_info()
  113. lines = traceback.format_exception(e_type, e_value, e_tb)
  114. traceback_msg = ''.join(lines)
  115. popup(title=toast_msg, content=put_error(traceback_msg), size=PopupSize.LARGE)
  116. run_js("console.error(traceback_msg)", traceback_msg='Internal Server Error\n' + traceback_msg)
  117. else:
  118. toast(toast_msg, duration=1, color='error')
  119. except Exception:
  120. pass
  121. def register_callback(self, callback, **options):
  122. """ 向Session注册一个回调函数,返回回调id
  123. Session需要保证当收到前端发送的事件消息 ``{event: "callback",task_id: 回调id, data:...}`` 时,
  124. ``callback`` 回调函数被执行, 并传入事件消息中的 ``data`` 字段值作为参数
  125. """
  126. raise NotImplementedError
  127. def defer_call(self, func):
  128. """设置会话结束时调用的函数。可以用于资源清理。
  129. 在会话中可以多次调用 `defer_call()` ,会话结束后将会顺序执行设置的函数。
  130. :param func: 话结束时调用的函数
  131. """
  132. """设置会话结束时调用的函数。可以用于资源清理。"""
  133. self.deferred_functions.append(func)
  134. def need_keep_alive(self) -> bool:
  135. raise NotImplementedError
  136. def get_session_info_from_headers(headers):
  137. """从Http请求头中获取会话信息
  138. :param headers: 字典类型的Http请求头
  139. :return: 表示会话信息的对象,属性有:
  140. * ``user_agent`` : 用户浏览器信息。可用字段见 https://github.com/selwin/python-user-agents#usage
  141. * ``user_language`` : 用户操作系统使用的语言
  142. * ``server_host`` : 当前会话的服务器host,包含域名和端口,端口为80时可以被省略
  143. * ``origin`` : 当前用户的页面地址. 包含 协议、主机、端口 部分. 比如 ``'http://localhost:8080'`` .
  144. 可能为空,但保证当用户的页面地址不在当前服务器下(即 主机、端口部分和 ``server_host`` 不一致)时有值.
  145. """
  146. ua_str = headers.get('User-Agent', '')
  147. ua = user_agents.parse(ua_str)
  148. user_language = headers.get('Accept-Language', '').split(',', 1)[0].split(' ', 1)[0].split(';', 1)[0]
  149. server_host = headers.get('Host', '')
  150. origin = headers.get('Origin', '')
  151. session_info = dict(user_agent=ua, user_language=user_language,
  152. server_host=server_host, origin=origin)
  153. return session_info