io_ctrl.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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.custom_enter = None
  63. self.custom_exit = None
  64. def enable_context_manager(self, container_selector=None, container_dom_id=None, custom_enter=None,
  65. custom_exit=None):
  66. self.enabled_context_manager = True
  67. self.container_selector = container_selector
  68. self.container_dom_id = container_dom_id
  69. self.custom_enter = custom_enter
  70. self.custom_exit = custom_exit
  71. return self
  72. def __enter__(self):
  73. if not self.enabled_context_manager:
  74. raise RuntimeError("This output function can't be used as context manager!")
  75. if self.custom_enter:
  76. return self.custom_enter(self)
  77. self.container_dom_id = self.container_dom_id or random_str(10)
  78. self.spec['container_selector'] = self.container_selector
  79. self.spec['container_dom_id'] = scope2dom(self.container_dom_id, no_css_selector=True)
  80. self.send()
  81. get_current_session().push_scope(self.container_dom_id)
  82. return self.container_dom_id
  83. def __exit__(self, exc_type, exc_val, exc_tb):
  84. """
  85. If this method returns True,
  86. it means that the context manager can handle the exception,
  87. so that the with statement terminates the propagation of the exception
  88. """
  89. if self.custom_exit:
  90. return self.custom_exit(self, exc_type=exc_type, exc_val=exc_val, exc_tb=exc_tb)
  91. get_current_session().pop_scope()
  92. return False # Propagate Exception
  93. def embed_data(self):
  94. """返回供嵌入到其他消息中的数据,可以设置一些默认值"""
  95. self.processed = True
  96. return self.on_embed(self.spec)
  97. def send(self):
  98. """发送输出内容到Client"""
  99. self.processed = True
  100. send_msg('output', self.spec)
  101. show = send # `show` is a more user-friendly name
  102. def style(self, css_style):
  103. """Set css style for output
  104. :param str css_style: CSS style string
  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 onclick(self, callback):
  116. """Add click callback to this widget.
  117. :param callable callback: Callback which will be called when the widget is clicked.
  118. """
  119. callback_id = output_register_callback(lambda _: callback())
  120. self.spec.setdefault('click_callback_id', '')
  121. self.spec['click_callback_id'] += callback_id
  122. return self
  123. def __del__(self):
  124. """返回值没有被变量接收时的操作:直接输出消息"""
  125. if not self.processed:
  126. self.send()
  127. class OutputList(UserList):
  128. """
  129. 用于 style 对输出列表设置样式时的返回值
  130. """
  131. def __del__(self):
  132. """返回值没有被变量接收时的操作:顺序输出其持有的内容"""
  133. for o in self.data:
  134. o.__del__()
  135. def safely_destruct_output_when_exp(content_param):
  136. """装饰器生成: 异常时安全释放 Output 对象
  137. :param content_param: 含有Output实例的参数名或参数名列表
  138. :type content_param: list/str
  139. :return: 装饰器
  140. """
  141. def decorator(func):
  142. sig = inspect.signature(func)
  143. @wraps(func)
  144. def inner(*args, **kwargs):
  145. try:
  146. return func(*args, **kwargs)
  147. except Exception:
  148. # 发生异常,安全地释放 Output 对象
  149. params = [content_param] if isinstance(content_param, str) else content_param
  150. bound = sig.bind(*args, **kwargs).arguments
  151. for param in params:
  152. if bound.get(param):
  153. Output.safely_destruct(bound.get(param))
  154. raise
  155. return inner
  156. return decorator
  157. def send_msg(cmd, spec=None, task_id=None):
  158. msg = dict(command=cmd, spec=spec, task_id=task_id or get_current_task_id())
  159. get_current_session().send_task_command(msg)
  160. def single_input_kwargs(single_input_return):
  161. try:
  162. # 协程模式下,单项输入为协程对象,可以通过send(None)来获取传入单项输入的参数字典
  163. # In the coroutine mode, the item of `inputs` is coroutine object.
  164. # using `send(None)` to get the single input function's parameter dict.
  165. single_input_return.send(None)
  166. except StopIteration as e: # This is in the coroutine mode
  167. input_kwargs = e.args[0]
  168. except AttributeError: # This is in the thread mode
  169. input_kwargs = single_input_return
  170. else:
  171. raise RuntimeError("Can't get kwargs from single input")
  172. return input_kwargs
  173. @chose_impl
  174. def single_input(item_spec, valid_func, preprocess_func, onchange_func):
  175. """
  176. Note: 鲁棒性在上层完成
  177. 将单个input构造成input_group,并获取返回值
  178. :param item_spec: 单个输入项的参数 'name' must in item_spec, 参数一定已经验证通过
  179. :param valid_func: Not None
  180. :param onchange_func: Not None
  181. :param preprocess_func: Not None, 预处理函数,在收到用户提交的单项输入的原始数据后用于在校验前对数据进行预处理
  182. """
  183. if item_spec.get('name') is None: # single input
  184. item_spec['name'] = 'data'
  185. else: # as input_group item
  186. # use `single_input_kwargs()` to get the returned value
  187. return dict(item_spec=item_spec, valid_func=valid_func,
  188. preprocess_func=preprocess_func, onchange_func=onchange_func)
  189. label = item_spec['label']
  190. name = item_spec['name']
  191. # todo 是否可以原地修改spec
  192. item_spec['label'] = ''
  193. item_spec.setdefault('auto_focus', True) # 如果没有设置autofocus参数,则开启参数 todo CHECKBOX, RADIO 特殊处理
  194. spec = dict(label=label, inputs=[item_spec])
  195. data = yield input_control(spec=spec,
  196. preprocess_funcs={name: preprocess_func},
  197. item_valid_funcs={name: valid_func},
  198. onchange_funcs={name: onchange_func})
  199. return data[name]
  200. @chose_impl
  201. def input_control(spec, preprocess_funcs, item_valid_funcs, onchange_funcs, form_valid_funcs=None):
  202. """
  203. 发送input命令,监听事件,验证输入项,返回结果
  204. :param spec:
  205. :param preprocess_funcs: keys 严格等于 spec中的name集合
  206. :param item_valid_funcs: keys 严格等于 spec中的name集合
  207. :param onchange_funcs: keys 严格等于 spec中的name集合
  208. :param form_valid_funcs: can be ``None``
  209. :return:
  210. """
  211. send_msg('input_group', spec)
  212. data = yield input_event_handle(item_valid_funcs, form_valid_funcs, preprocess_funcs, onchange_funcs)
  213. send_msg('destroy_form')
  214. return data
  215. def check_item(name, data, valid_func, preprocess_func):
  216. try:
  217. data = preprocess_func(data)
  218. error_msg = valid_func(data)
  219. except Exception as e:
  220. logger.warning('Get %r in valid_func for name:"%s"', e, name)
  221. from pywebio.session import info as session_info
  222. error_msg = '字段内容不合法' if 'zh' in session_info.user_language else 'Your input is not valid'
  223. if error_msg is not None:
  224. send_msg('update_input', dict(target_name=name, attributes={
  225. 'valid_status': False,
  226. 'invalid_feedback': error_msg
  227. }))
  228. return False
  229. else:
  230. send_msg('update_input', dict(target_name=name, attributes={
  231. 'valid_status': 0, # valid_status为0表示清空valid_status标志
  232. }))
  233. return True
  234. def trigger_onchange(event_data, onchange_funcs):
  235. name = event_data['name']
  236. onchange_func = onchange_funcs[name]
  237. task_id = get_current_task_id()
  238. get_current_session().internal_save['onchange_trigger-' + task_id] = name # used in `pywebio.input.input_update()`
  239. try:
  240. onchange_func(event_data['value'])
  241. except Exception as e:
  242. logger.warning('Get %r in onchange function for name:"%s"', e, name)
  243. finally:
  244. del get_current_session().internal_save['onchange_trigger-' + task_id]
  245. @chose_impl
  246. def input_event_handle(item_valid_funcs, form_valid_funcs, preprocess_funcs, onchange_funcs):
  247. """
  248. 根据提供的校验函数处理表单事件
  249. :param item_valid_funcs: map(name -> valid_func) valid_func 为 None 时,不进行验证
  250. valid_func: callback(data) -> error_msg or None
  251. :param form_valid_funcs: callback(data) -> (name, error_msg) or None
  252. :param preprocess_funcs: map(name -> process_func)
  253. :param onchange_funcs: map(name -> onchange_func)
  254. :return:
  255. """
  256. while True:
  257. event = yield next_client_event()
  258. event_name, event_data = event['event'], event['data']
  259. if event_name == 'input_event':
  260. input_event = event_data['event_name']
  261. if input_event == 'blur':
  262. onblur_name = event_data['name']
  263. check_item(onblur_name, event_data['value'], item_valid_funcs[onblur_name],
  264. preprocess_funcs[onblur_name])
  265. elif input_event == 'change':
  266. trigger_onchange(event_data, onchange_funcs)
  267. elif event_name == 'from_submit':
  268. all_valid = True
  269. # 调用输入项验证函数进行校验
  270. for name, valid_func in item_valid_funcs.items():
  271. if not check_item(name, event_data[name], valid_func, preprocess_funcs[name]):
  272. all_valid = False
  273. if all_valid: # todo 减少preprocess_funcs[name]调用次数
  274. data = {name: preprocess_funcs[name](val) for name, val in event_data.items()}
  275. # 调用表单验证函数进行校验
  276. if form_valid_funcs:
  277. v_res = form_valid_funcs(data)
  278. if v_res is not None:
  279. all_valid = False
  280. try:
  281. onblur_name, error_msg = v_res
  282. except Exception:
  283. # Use `raise Exception from None` to disable exception chaining
  284. # see: https://docs.python.org/3/tutorial/errors.html#exception-chaining
  285. raise ValueError("The `validate` function for input group must "
  286. "return `(name, error_msg)` when validation failed.") from None
  287. send_msg('update_input', dict(target_name=onblur_name, attributes={
  288. 'valid_status': False,
  289. 'invalid_feedback': error_msg
  290. }))
  291. if all_valid:
  292. break
  293. elif event_name == 'from_cancel':
  294. data = None
  295. break
  296. else:
  297. logger.warning("Unhandled Event: %s", event)
  298. return data
  299. def output_register_callback(callback, **options):
  300. """向当前会话注册毁掉函数"""
  301. task_id = get_current_session().register_callback(callback, **options)
  302. return task_id