io_ctrl.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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 collections.abc import Mapping
  10. from .session import chose_impl, next_client_event, get_current_task_id, get_current_session
  11. from .utils import random_str
  12. logger = logging.getLogger(__name__)
  13. def scope2dom(name, no_css_selector=False):
  14. """Get the CSS selector/element name actually used in the front-end html page
  15. :param str/tuple name: When it is str, it is regarded as the Dom ID name;
  16. when tuple, the format is (css selector, element name)
  17. """
  18. selector = '#'
  19. if isinstance(name, tuple):
  20. selector, name = name
  21. name = name.replace(' ', '-')
  22. if no_css_selector:
  23. selector = ''
  24. return '%spywebio-scope-%s' % (selector, name)
  25. class Output:
  26. """ ``put_xxx()`` 类函数的返回值
  27. 若 ``put_xxx()`` 调用的返回值没有被变量接收,则直接将消息发送到会话;
  28. 否则消息则作为其他消息的一部分
  29. """
  30. @staticmethod
  31. def json_encoder(obj, ignore_error=False):
  32. """json序列化与输出相关消息的Encoder函数 """
  33. if isinstance(obj, Output):
  34. return obj.embed_data()
  35. elif isinstance(obj, OutputList):
  36. return obj.data
  37. if not ignore_error:
  38. raise TypeError('Object of type %s is not JSON serializable' % obj.__class__.__name__)
  39. @classmethod
  40. def dump_dict(cls, data):
  41. # todo 使用其他方式来转换spec
  42. return json.loads(json.dumps(data, default=cls.json_encoder))
  43. @classmethod
  44. def safely_destruct(cls, obj):
  45. """安全销毁 OutputReturn 对象/包含OutputReturn对象的dict/list, 使 OutputReturn.__del__ 不进行任何操作"""
  46. try:
  47. json.dumps(obj, default=partial(cls.json_encoder, ignore_error=True))
  48. except Exception:
  49. pass
  50. def __init__(self, spec, on_embed=None):
  51. self.processed = False
  52. self.on_embed = on_embed or (lambda d: d)
  53. try:
  54. self.spec = type(self).dump_dict(spec) # this may raise TypeError
  55. except TypeError:
  56. self.processed = True
  57. type(self).safely_destruct(spec)
  58. raise
  59. # For Context manager
  60. self.enabled_context_manager = False
  61. self.container_selector = None
  62. self.container_dom_id = None # todo: this name is ambiguous, rename it to `scope_name` or others
  63. self.custom_enter = None
  64. self.custom_exit = None
  65. def enable_context_manager(self, container_selector=None, container_dom_id=None, custom_enter=None,
  66. custom_exit=None):
  67. self.enabled_context_manager = True
  68. self.container_selector = container_selector
  69. self.container_dom_id = container_dom_id
  70. self.custom_enter = custom_enter
  71. self.custom_exit = custom_exit
  72. return self
  73. def __enter__(self):
  74. if not self.enabled_context_manager:
  75. raise RuntimeError("This output function can't be used as context manager!")
  76. if self.custom_enter:
  77. return self.custom_enter(self)
  78. self.container_dom_id = self.container_dom_id or random_str(10)
  79. self.spec['container_selector'] = self.container_selector
  80. self.spec['container_dom_id'] = scope2dom(self.container_dom_id, no_css_selector=True)
  81. self.send()
  82. get_current_session().push_scope(self.container_dom_id)
  83. return self.container_dom_id
  84. def __exit__(self, exc_type, exc_val, exc_tb):
  85. """
  86. If this method returns True,
  87. it means that the context manager can handle the exception,
  88. so that the with statement terminates the propagation of the exception
  89. """
  90. if self.custom_exit:
  91. return self.custom_exit(self, exc_type=exc_type, exc_val=exc_val, exc_tb=exc_tb)
  92. get_current_session().pop_scope()
  93. return False # Propagate Exception
  94. def embed_data(self):
  95. """返回供嵌入到其他消息中的数据,可以设置一些默认值"""
  96. self.processed = True
  97. return self.on_embed(self.spec)
  98. def send(self):
  99. """发送输出内容到Client"""
  100. self.processed = True
  101. send_msg('output', self.spec)
  102. show = send # `show` is a more user-friendly name
  103. def style(self, css_style):
  104. """Set css style for output
  105. Example::
  106. put_text('hello').style('color: red; font-size: 20px')
  107. put_row([
  108. put_text('hello').style('color: red'),
  109. put_markdown('markdown')
  110. ]).style('margin-top: 20px')
  111. """
  112. self.spec.setdefault('style', '')
  113. self.spec['style'] += ';%s' % css_style
  114. return self
  115. def __del__(self):
  116. """返回值没有被变量接收时的操作:直接输出消息"""
  117. if not self.processed:
  118. self.send()
  119. class OutputList(UserList):
  120. """
  121. 用于 style 对输出列表设置样式时的返回值
  122. """
  123. def __del__(self):
  124. """返回值没有被变量接收时的操作:顺序输出其持有的内容"""
  125. for o in self.data:
  126. o.__del__()
  127. def safely_destruct_output_when_exp(content_param):
  128. """装饰器生成: 异常时安全释放 Output 对象
  129. :param content_param: 含有Output实例的参数名或参数名列表
  130. :type content_param: list/str
  131. :return: 装饰器
  132. """
  133. def decorator(func):
  134. sig = inspect.signature(func)
  135. @wraps(func)
  136. def inner(*args, **kwargs):
  137. try:
  138. return func(*args, **kwargs)
  139. except Exception:
  140. # 发生异常,安全地释放 Output 对象
  141. params = [content_param] if isinstance(content_param, str) else content_param
  142. bound = sig.bind(*args, **kwargs).arguments
  143. for param in params:
  144. if bound.get(param):
  145. Output.safely_destruct(bound.get(param))
  146. raise
  147. return inner
  148. return decorator
  149. def send_msg(cmd, spec=None, task_id=None):
  150. msg = dict(command=cmd, spec=spec, task_id=task_id or get_current_task_id())
  151. get_current_session().send_task_command(msg)
  152. def single_input_kwargs(single_input_return):
  153. try:
  154. # 协程模式下,单项输入为协程对象,可以通过send(None)来获取传入单项输入的参数字典
  155. # In the coroutine mode, the item of `inputs` is coroutine object.
  156. # using `send(None)` to get the single input function's parameter dict.
  157. single_input_return.send(None)
  158. except StopIteration as e: # This is in the coroutine mode
  159. input_kwargs = e.args[0]
  160. except AttributeError: # This is in the thread mode
  161. input_kwargs = single_input_return
  162. else:
  163. raise RuntimeError("Can't get kwargs from single input")
  164. return input_kwargs
  165. @chose_impl
  166. def single_input(item_spec, valid_func, preprocess_func, onchange_func):
  167. """
  168. Note: 鲁棒性在上层完成
  169. 将单个input构造成input_group,并获取返回值
  170. :param item_spec: 单个输入项的参数 'name' must in item_spec, 参数一定已经验证通过
  171. :param valid_func: Not None
  172. :param onchange_func: Not None
  173. :param preprocess_func: Not None, 预处理函数,在收到用户提交的单项输入的原始数据后用于在校验前对数据进行预处理
  174. """
  175. if item_spec.get('name') is None: # single input
  176. item_spec['name'] = 'data'
  177. else: # as input_group item
  178. # use `single_input_kwargs()` to get the returned value
  179. return dict(item_spec=item_spec, valid_func=valid_func,
  180. preprocess_func=preprocess_func, onchange_func=onchange_func)
  181. label = item_spec['label']
  182. name = item_spec['name']
  183. # todo 是否可以原地修改spec
  184. item_spec['label'] = ''
  185. item_spec.setdefault('auto_focus', True) # 如果没有设置autofocus参数,则开启参数 todo CHECKBOX, RADIO 特殊处理
  186. spec = dict(label=label, inputs=[item_spec])
  187. data = yield input_control(spec=spec,
  188. preprocess_funcs={name: preprocess_func},
  189. item_valid_funcs={name: valid_func},
  190. onchange_funcs={name: onchange_func})
  191. return data[name]
  192. @chose_impl
  193. def input_control(spec, preprocess_funcs, item_valid_funcs, onchange_funcs, form_valid_funcs=None):
  194. """
  195. 发送input命令,监听事件,验证输入项,返回结果
  196. :param spec:
  197. :param preprocess_funcs: keys 严格等于 spec中的name集合
  198. :param item_valid_funcs: keys 严格等于 spec中的name集合
  199. :param onchange_funcs: keys 严格等于 spec中的name集合
  200. :param form_valid_funcs: can be ``None``
  201. :return:
  202. """
  203. send_msg('input_group', spec)
  204. data = yield input_event_handle(item_valid_funcs, form_valid_funcs, preprocess_funcs, onchange_funcs)
  205. send_msg('destroy_form')
  206. return data
  207. def check_item(name, data, valid_func, preprocess_func):
  208. try:
  209. data = preprocess_func(data)
  210. error_msg = valid_func(data)
  211. except Exception as e:
  212. logger.warning('Get %r in valid_func for name:"%s"', e, name)
  213. from pywebio.session import info as session_info
  214. error_msg = '字段内容不合法' if 'zh' in session_info.user_language else 'Your input is not valid'
  215. if error_msg is not None:
  216. send_msg('update_input', dict(target_name=name, attributes={
  217. 'valid_status': False,
  218. 'invalid_feedback': error_msg
  219. }))
  220. return False
  221. else:
  222. send_msg('update_input', dict(target_name=name, attributes={
  223. 'valid_status': 0, # valid_status为0表示清空valid_status标志
  224. }))
  225. return True
  226. def trigger_onchange(event_data, onchange_funcs):
  227. name = event_data['name']
  228. onchange_func = onchange_funcs[name]
  229. task_id = get_current_task_id()
  230. get_current_session().internal_save['onchange_trigger-' + task_id] = name # used in `pywebio.input.input_update()`
  231. try:
  232. onchange_func(event_data['value'])
  233. except Exception as e:
  234. logger.warning('Get %r in onchange function for name:"%s"', e, name)
  235. finally:
  236. del get_current_session().internal_save['onchange_trigger-' + task_id]
  237. @chose_impl
  238. def input_event_handle(item_valid_funcs, form_valid_funcs, preprocess_funcs, onchange_funcs):
  239. """
  240. 根据提供的校验函数处理表单事件
  241. :param item_valid_funcs: map(name -> valid_func) valid_func 为 None 时,不进行验证
  242. valid_func: callback(data) -> error_msg or None
  243. :param form_valid_funcs: callback(data) -> (name, error_msg) or None
  244. :param preprocess_funcs: map(name -> process_func)
  245. :param onchange_funcs: map(name -> onchange_func)
  246. :return:
  247. """
  248. while True:
  249. event = yield next_client_event()
  250. event_name, event_data = event['event'], event['data']
  251. if event_name == 'input_event':
  252. input_event = event_data['event_name']
  253. if input_event == 'blur':
  254. onblur_name = event_data['name']
  255. check_item(onblur_name, event_data['value'], item_valid_funcs[onblur_name],
  256. preprocess_funcs[onblur_name])
  257. elif input_event == 'change':
  258. trigger_onchange(event_data, onchange_funcs)
  259. elif event_name == 'from_submit':
  260. all_valid = True
  261. # 调用输入项验证函数进行校验
  262. for name, valid_func in item_valid_funcs.items():
  263. if not check_item(name, event_data[name], valid_func, preprocess_funcs[name]):
  264. all_valid = False
  265. if all_valid: # todo 减少preprocess_funcs[name]调用次数
  266. data = {name: preprocess_funcs[name](val) for name, val in event_data.items()}
  267. # 调用表单验证函数进行校验
  268. if form_valid_funcs:
  269. v_res = form_valid_funcs(data)
  270. if v_res is not None:
  271. all_valid = False
  272. try:
  273. onblur_name, error_msg = v_res
  274. except Exception:
  275. raise ValueError("The `validate` function for input group must "
  276. "return `(name, error_msg)` when validation failed.")
  277. send_msg('update_input', dict(target_name=onblur_name, attributes={
  278. 'valid_status': False,
  279. 'invalid_feedback': error_msg
  280. }))
  281. if all_valid:
  282. break
  283. elif event_name == 'from_cancel':
  284. data = None
  285. break
  286. else:
  287. logger.warning("Unhandled Event: %s", event)
  288. return data
  289. def output_register_callback(callback, **options):
  290. """向当前会话注册毁掉函数"""
  291. task_id = get_current_session().register_callback(callback, **options)
  292. return task_id