io_ctrl.py 14 KB

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