io_ctrl.py 7.8 KB

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