io_ctrl.py 7.1 KB

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