io_ctrl.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. """
  2. 输入输出的底层实现函数
  3. """
  4. import inspect
  5. import json
  6. import logging
  7. from collections import UserList
  8. from functools import partial, wraps
  9. from .session import chose_impl, next_client_event, get_current_task_id, get_current_session
  10. from .utils import random_str
  11. logger = logging.getLogger(__name__)
  12. class Output:
  13. """ ``put_xxx()`` 类函数的返回值
  14. 若 ``put_xxx()`` 调用的返回值没有被变量接收,则直接将消息发送到会话;
  15. 否则消息则作为其他消息的一部分
  16. """
  17. @staticmethod
  18. def json_encoder(obj, ignore_error=False):
  19. """json序列化与输出相关消息的Encoder函数 """
  20. if isinstance(obj, Output):
  21. return obj.embed_data()
  22. elif isinstance(obj, OutputList):
  23. return obj.data
  24. if not ignore_error:
  25. raise TypeError('Object of type %s is not JSON serializable' % obj.__class__.__name__)
  26. @classmethod
  27. def dump_dict(cls, data):
  28. # todo 使用其他方式来转换spec
  29. return json.loads(json.dumps(data, default=cls.json_encoder))
  30. @classmethod
  31. def safely_destruct(cls, obj):
  32. """安全销毁 OutputReturn 对象/包含OutputReturn对象的dict/list, 使 OutputReturn.__del__ 不进行任何操作"""
  33. try:
  34. json.dumps(obj, default=partial(cls.json_encoder, ignore_error=True))
  35. except Exception:
  36. pass
  37. def __init__(self, spec, on_embed=None):
  38. self.processed = False
  39. self.on_embed = on_embed or (lambda d: d)
  40. try:
  41. self.spec = type(self).dump_dict(spec) # this may raise TypeError
  42. except TypeError:
  43. self.processed = True
  44. type(self).safely_destruct(spec)
  45. raise
  46. # For Context manager
  47. self.enabled_context_manager = False
  48. self.container_selector = None
  49. self.container_dom_id = None
  50. self.custom_enter = None
  51. self.custom_exit = None
  52. def enable_context_manager(self, container_selector=None, container_dom_id=None, custom_enter=None,
  53. custom_exit=None):
  54. self.enabled_context_manager = True
  55. self.container_selector = container_selector
  56. self.container_dom_id = container_dom_id
  57. self.custom_enter = custom_enter
  58. self.custom_exit = custom_exit
  59. return self
  60. def __enter__(self):
  61. if not self.enabled_context_manager:
  62. raise RuntimeError("This output function can't be used as context manager!")
  63. r = self.custom_enter(self) if self.custom_enter else None
  64. if r is not None:
  65. return r
  66. self.container_dom_id = self.container_dom_id or random_str(10)
  67. self.spec['container_selector'] = self.container_selector
  68. self.spec['container_dom_id'] = self.container_dom_id
  69. self.send()
  70. get_current_session().push_scope(self.container_dom_id)
  71. return self.container_dom_id
  72. def __exit__(self, exc_type, exc_val, exc_tb):
  73. """
  74. If this method returns True,
  75. it means that the context manager can handle the exception,
  76. so that the with statement terminates the propagation of the exception
  77. """
  78. r = self.custom_exit(self, exc_type=exc_type, exc_val=exc_val, exc_tb=exc_tb) if self.custom_exit else None
  79. if r is not None:
  80. return r
  81. get_current_session().pop_scope()
  82. return False # Propagate Exception
  83. def embed_data(self):
  84. """返回供嵌入到其他消息中的数据,可以设置一些默认值"""
  85. self.processed = True
  86. return self.on_embed(self.spec)
  87. def send(self):
  88. """发送输出内容到Client"""
  89. self.processed = True
  90. send_msg('output', self.spec)
  91. def __del__(self):
  92. """返回值没有被变量接收时的操作:直接输出消息"""
  93. if not self.processed:
  94. self.send()
  95. class OutputList(UserList):
  96. """
  97. 用于 style 对输出列表设置样式时的返回值
  98. """
  99. def __del__(self):
  100. """返回值没有被变量接收时的操作:顺序输出其持有的内容"""
  101. for o in self.data:
  102. o.__del__()
  103. def safely_destruct_output_when_exp(content_param):
  104. """装饰器生成: 异常时安全释放 Output 对象
  105. :param content_param: 含有Output实例的参数名或参数名列表
  106. :type content_param: list/str
  107. :return: 装饰器
  108. """
  109. def decorator(func):
  110. sig = inspect.signature(func)
  111. @wraps(func)
  112. def inner(*args, **kwargs):
  113. try:
  114. return func(*args, **kwargs)
  115. except Exception:
  116. # 发生异常,安全地释放 Output 对象
  117. params = [content_param] if isinstance(content_param, str) else content_param
  118. bound = sig.bind(*args, **kwargs).arguments
  119. for param in params:
  120. if bound.get(param):
  121. Output.safely_destruct(bound.get(param))
  122. raise
  123. return inner
  124. return decorator
  125. def send_msg(cmd, spec=None):
  126. msg = dict(command=cmd, spec=spec, task_id=get_current_task_id())
  127. get_current_session().send_task_command(msg)
  128. @chose_impl
  129. def single_input(item_spec, valid_func, preprocess_func):
  130. """
  131. Note: 鲁棒性在上层完成
  132. 将单个input构造成input_group,并获取返回值
  133. :param item_spec: 单个输入项的参数 'name' must in item_spec, 参数一定已经验证通过
  134. :param valid_func: Not None
  135. :param preprocess_func: Not None, 预处理函数,在收到用户提交的单项输入的原始数据后用于在校验前对数据进行预处理
  136. """
  137. if item_spec.get('name') is None: # single input
  138. item_spec['name'] = 'data'
  139. else: # as input_group item
  140. return dict(item_spec=item_spec, valid_func=valid_func, preprocess_func=preprocess_func)
  141. label = item_spec['label']
  142. name = item_spec['name']
  143. # todo 是否可以原地修改spec
  144. item_spec['label'] = ''
  145. item_spec.setdefault('auto_focus', True) # 如果没有设置autofocus参数,则开启参数 todo CHECKBOX, RADIO 特殊处理
  146. spec = dict(label=label, inputs=[item_spec])
  147. data = yield input_control(spec, {name: preprocess_func}, {name: valid_func})
  148. return data[name]
  149. @chose_impl
  150. def input_control(spec, preprocess_funcs, item_valid_funcs, form_valid_funcs=None):
  151. """
  152. 发送input命令,监听事件,验证输入项,返回结果
  153. :param spec:
  154. :param preprocess_funcs: keys 严格等于 spec中的name集合
  155. :param item_valid_funcs: keys 严格等于 spec中的name集合
  156. :param form_valid_funcs:
  157. :return:
  158. """
  159. send_msg('input_group', spec)
  160. data = yield input_event_handle(item_valid_funcs, form_valid_funcs, preprocess_funcs)
  161. send_msg('destroy_form')
  162. return data
  163. def check_item(name, data, valid_func, preprocess_func):
  164. try:
  165. data = preprocess_func(data)
  166. error_msg = valid_func(data)
  167. except Exception as e:
  168. logger.warning('Get %r in valid_func for name:"%s"', e, name)
  169. from pywebio.session import info as session_info
  170. error_msg = '字段内容不合法' if 'zh' in session_info.user_language else 'Your input is not valid'
  171. if error_msg is not None:
  172. send_msg('update_input', dict(target_name=name, attributes={
  173. 'valid_status': False,
  174. 'invalid_feedback': error_msg
  175. }))
  176. return False
  177. else:
  178. send_msg('update_input', dict(target_name=name, attributes={
  179. 'valid_status': 0, # valid_status为0表示清空valid_status标志
  180. }))
  181. return True
  182. @chose_impl
  183. def input_event_handle(item_valid_funcs, form_valid_funcs, preprocess_funcs):
  184. """
  185. 根据提供的校验函数处理表单事件
  186. :param item_valid_funcs: map(name -> valid_func) valid_func 为 None 时,不进行验证
  187. valid_func: callback(data) -> error_msg or None
  188. :param form_valid_funcs: callback(data) -> (name, error_msg) or None
  189. :param preprocess_funcs:
  190. :return:
  191. """
  192. while True:
  193. event = yield next_client_event()
  194. event_name, event_data = event['event'], event['data']
  195. if event_name == 'input_event':
  196. input_event = event_data['event_name']
  197. if input_event == 'blur':
  198. onblur_name = event_data['name']
  199. check_item(onblur_name, event_data['value'], item_valid_funcs[onblur_name],
  200. preprocess_funcs[onblur_name])
  201. elif event_name == 'from_submit':
  202. all_valid = True
  203. # 调用输入项验证函数进行校验
  204. for name, valid_func in item_valid_funcs.items():
  205. if not check_item(name, event_data[name], valid_func, preprocess_funcs[name]):
  206. all_valid = False
  207. if all_valid: # todo 减少preprocess_funcs[name]调用次数
  208. data = {name: preprocess_funcs[name](val) for name, val in event_data.items()}
  209. # 调用表单验证函数进行校验
  210. if form_valid_funcs:
  211. v_res = form_valid_funcs(data)
  212. if v_res is not None:
  213. all_valid = False
  214. onblur_name, error_msg = v_res
  215. send_msg('update_input', dict(target_name=onblur_name, attributes={
  216. 'valid_status': False,
  217. 'invalid_feedback': error_msg
  218. }))
  219. if all_valid:
  220. break
  221. elif event_name == 'from_cancel':
  222. data = None
  223. break
  224. else:
  225. logger.warning("Unhandled Event: %s", event)
  226. return data
  227. def output_register_callback(callback, **options):
  228. """向当前会话注册毁掉函数"""
  229. task_id = get_current_session().register_callback(callback, **options)
  230. return task_id