output.py 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794
  1. r"""
  2. This module provides functions to output all kinds of content to the user's browser, and supply flexible output control.
  3. .. _output_func_list:
  4. Functions list
  5. ---------------
  6. ..
  7. Use https://www.tablesgenerator.com/text_tables to generate/update below table
  8. | The following table shows the output-related functions provided by PyWebIO.
  9. | The functions marked with ``*`` indicate that they accept ``put_xxx`` calls as arguments.
  10. | The functions marked with ``†`` indicate that they can use as context manager.
  11. +--------------------+---------------------------+------------------------------------------------------------+
  12. | | **Name** | **Description** |
  13. +--------------------+---------------------------+------------------------------------------------------------+
  14. | Output Scope | `put_scope` | Create a new scope |
  15. | +---------------------------+------------------------------------------------------------+
  16. | | `use_scope`:sup:`†` | Enter a scope |
  17. | +---------------------------+------------------------------------------------------------+
  18. | | `get_scope` | Get the current scope name in the runtime scope stack |
  19. | +---------------------------+------------------------------------------------------------+
  20. | | `clear` | Clear the content of scope |
  21. | +---------------------------+------------------------------------------------------------+
  22. | | `remove` | Remove the scope |
  23. | +---------------------------+------------------------------------------------------------+
  24. | | `scroll_to` | Scroll the page to the scope |
  25. +--------------------+---------------------------+------------------------------------------------------------+
  26. | Content Outputting | `put_text` | Output plain text |
  27. | +---------------------------+------------------------------------------------------------+
  28. | | `put_markdown` | Output Markdown |
  29. | +---------------------------+------------------------------------------------------------+
  30. | | | `put_info`:sup:`*†` | Output Messages. |
  31. | | | `put_success`:sup:`*†` | |
  32. | | | `put_warning`:sup:`*†` | |
  33. | | | `put_error`:sup:`*†` | |
  34. | +---------------------------+------------------------------------------------------------+
  35. | | `put_html` | Output html |
  36. | +---------------------------+------------------------------------------------------------+
  37. | | `put_link` | Output link |
  38. | +---------------------------+------------------------------------------------------------+
  39. | | `put_processbar` | Output a process bar |
  40. | +---------------------------+------------------------------------------------------------+
  41. | | `set_processbar` | Set the progress of progress bar |
  42. | +---------------------------+------------------------------------------------------------+
  43. | | `put_loading`:sup:`†` | Output loading prompt |
  44. | +---------------------------+------------------------------------------------------------+
  45. | | `put_code` | Output code block |
  46. | +---------------------------+------------------------------------------------------------+
  47. | | `put_table`:sup:`*` | Output table |
  48. | +---------------------------+------------------------------------------------------------+
  49. | | | `put_button` | Output button and bind click event |
  50. | | | `put_buttons` | |
  51. | +---------------------------+------------------------------------------------------------+
  52. | | `put_image` | Output image |
  53. | +---------------------------+------------------------------------------------------------+
  54. | | `put_file` | Output a link to download a file |
  55. | +---------------------------+------------------------------------------------------------+
  56. | | `put_tabs`:sup:`*` | Output tabs |
  57. | +---------------------------+------------------------------------------------------------+
  58. | | `put_collapse`:sup:`*†` | Output collapsible content |
  59. | +---------------------------+------------------------------------------------------------+
  60. | | `put_scrollable`:sup:`*†` | | Output a fixed height content area, |
  61. | | | | scroll bar is displayed when the content |
  62. | | | | exceeds the limit |
  63. | +---------------------------+------------------------------------------------------------+
  64. | | `put_widget`:sup:`*` | Output your own widget |
  65. +--------------------+---------------------------+------------------------------------------------------------+
  66. | Other Interactions | `toast` | Show a notification message |
  67. | +---------------------------+------------------------------------------------------------+
  68. | | `popup`:sup:`*†` | Show popup |
  69. | +---------------------------+------------------------------------------------------------+
  70. | | `close_popup` | Close the current popup window. |
  71. +--------------------+---------------------------+------------------------------------------------------------+
  72. | Layout and Style | `put_row`:sup:`*†` | Use row layout to output content |
  73. | +---------------------------+------------------------------------------------------------+
  74. | | `put_column`:sup:`*†` | Use column layout to output content |
  75. | +---------------------------+------------------------------------------------------------+
  76. | | `put_grid`:sup:`*` | Output content using grid layout |
  77. | +---------------------------+------------------------------------------------------------+
  78. | | `span` | Cross-cell content |
  79. | +---------------------------+------------------------------------------------------------+
  80. | | `style`:sup:`*` | Customize the css style of output content |
  81. +--------------------+---------------------------+------------------------------------------------------------+
  82. Output Scope
  83. --------------
  84. .. seealso::
  85. * :ref:`Use Guide: Output Scope <output_scope>`
  86. .. autofunction:: put_scope
  87. .. autofunction:: use_scope
  88. .. autofunction:: get_scope
  89. .. autofunction:: clear
  90. .. autofunction:: remove
  91. .. autofunction:: scroll_to
  92. Content Outputting
  93. -----------------------
  94. .. _scope_param:
  95. **Scope related parameters of output function**
  96. The output function will output the content to the "current scope" by default, and the "current scope" for the runtime
  97. context can be set by `use_scope()`.
  98. In addition, all output functions support a ``scope`` parameter to specify the destination scope to output:
  99. .. exportable-codeblock::
  100. :name: put-xxx-scope
  101. :summary: ``scope`` parameter of the output function
  102. with use_scope('scope3'):
  103. put_text('text1 in scope3') # output to current scope: scope3
  104. put_text('text in ROOT scope', scope='ROOT') # output to ROOT Scope
  105. put_text('text2 in scope3', scope='scope3') # output to scope3
  106. The results of the above code are as follows::
  107. text1 in scope3
  108. text2 in scope3
  109. text in ROOT scope
  110. A scope can contain multiple output items, the default behavior of output function is to append its content to target scope.
  111. The ``position`` parameter of output function can be used to specify the insert position in target scope.
  112. Each output item in a scope has an index, the first item's index is 0, and the next item's index is incremented by one.
  113. You can also use a negative number to index the items in the scope, -1 means the last item, -2 means the item before the last, ...
  114. The ``position`` parameter of output functions accepts an integer. When ``position>=0``, it means to insert content
  115. before the item whose index equal ``position``; when ``position<0``, it means to insert content after the item whose
  116. index equal ``position``:
  117. .. exportable-codeblock::
  118. :name: put-xxx-position
  119. :summary: `position` parameter of the output function
  120. with use_scope('scope1'):
  121. put_text('A')
  122. ## ----
  123. with use_scope('scope1'): # ..demo-only
  124. put_text('B', position=0) # insert B before A -> B A
  125. ## ----
  126. with use_scope('scope1'): # ..demo-only
  127. put_text('C', position=-2) # insert C after B -> B C A
  128. ## ----
  129. with use_scope('scope1'): # ..demo-only
  130. put_text('D', position=1) # insert D before C B -> B D C A
  131. **Output functions**
  132. .. autofunction:: put_text
  133. .. autofunction:: put_markdown
  134. .. py:function:: put_info(*contents, closable=False, scope=None, position=-1) -> Output:
  135. put_success(*contents, closable=False, scope=None, position=-1) -> Output:
  136. put_warning(*contents, closable=False, scope=None, position=-1) -> Output:
  137. put_error(*contents, closable=False, scope=None, position=-1) -> Output:
  138. Output Messages.
  139. :param contents: Message contents.
  140. The item is ``put_xxx()`` call, and any other type will be converted to ``put_text(content)``.
  141. :param bool closable: Whether to show a dismiss button on the right of the message.
  142. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  143. .. versionadded:: 1.2
  144. .. autofunction:: put_html
  145. .. autofunction:: put_link
  146. .. autofunction:: put_processbar
  147. .. autofunction:: set_processbar
  148. .. autofunction:: put_loading
  149. .. autofunction:: put_code
  150. .. autofunction:: put_table
  151. .. autofunction:: span
  152. .. autofunction:: put_buttons
  153. .. autofunction:: put_button
  154. .. autofunction:: put_image
  155. .. autofunction:: put_file
  156. .. autofunction:: put_tabs
  157. .. autofunction:: put_collapse
  158. .. autofunction:: put_scrollable
  159. .. autofunction:: put_widget
  160. Other Interactions
  161. --------------------
  162. .. autofunction:: toast
  163. .. autofunction:: popup
  164. .. autofunction:: close_popup
  165. .. _style_and_layout:
  166. Layout and Style
  167. ------------------
  168. .. autofunction:: put_row
  169. .. autofunction:: put_column
  170. .. autofunction:: put_grid
  171. .. autofunction:: style
  172. """
  173. import html
  174. import io
  175. import logging
  176. import string
  177. from base64 import b64encode
  178. from collections.abc import Mapping, Sequence
  179. from functools import wraps
  180. from typing import Union
  181. from .io_ctrl import output_register_callback, send_msg, Output, safely_destruct_output_when_exp, OutputList, scope2dom
  182. from .session import get_current_session, download
  183. from .utils import random_str, iscoroutinefunction, is_html_safe_value
  184. try:
  185. from PIL.Image import Image as PILImage
  186. except ImportError:
  187. PILImage = type('MockPILImage', (), dict(__init__=None))
  188. logger = logging.getLogger(__name__)
  189. __all__ = ['Position', 'remove', 'scroll_to', 'put_tabs', 'put_scope',
  190. 'put_text', 'put_html', 'put_code', 'put_markdown', 'use_scope', 'set_scope', 'clear', 'remove',
  191. 'put_table', 'put_buttons', 'put_image', 'put_file', 'PopupSize', 'popup', 'put_button',
  192. 'close_popup', 'put_widget', 'put_collapse', 'put_link', 'put_scrollable', 'style', 'put_column',
  193. 'put_row', 'put_grid', 'span', 'put_processbar', 'set_processbar', 'put_loading',
  194. 'output', 'toast', 'get_scope', 'put_info', 'put_error', 'put_warning', 'put_success']
  195. # popup size
  196. class PopupSize:
  197. LARGE = 'large'
  198. NORMAL = 'normal'
  199. SMALL = 'small'
  200. class Position:
  201. TOP = 'top'
  202. MIDDLE = 'middle'
  203. BOTTOM = 'bottom'
  204. # position value of `put_xxx()`
  205. class OutputPosition:
  206. TOP = 0
  207. BOTTOM = -1
  208. _scope_name_allowed_chars = set(string.ascii_letters + string.digits + '_-')
  209. def set_scope(name, container_scope=None, position=OutputPosition.BOTTOM, if_exist=None):
  210. """Create a new scope.
  211. :param str name: scope name
  212. :param str container_scope: Specify the parent scope of this scope.
  213. When the scope doesn't exist, no operation is performed.
  214. :param int position: The location where this scope is created in the parent scope.
  215. (see :ref:`Scope related parameters <scope_param>`)
  216. :param str if_exist: What to do when the specified scope already exists:
  217. - `None`: Do nothing
  218. - `'remove'`: Remove the old scope first and then create a new one
  219. - `'clear'`: Just clear the contents of the old scope, but don't create a new scope
  220. Default is `None`
  221. """
  222. if container_scope is None:
  223. container_scope = get_scope()
  224. assert is_html_safe_value(name), "Scope name only allow letter/digit/'_'/'-' char."
  225. send_msg('output_ctl', dict(set_scope=scope2dom(name, no_css_selector=True),
  226. container=scope2dom(container_scope),
  227. position=position, if_exist=if_exist))
  228. def get_scope(stack_idx=-1):
  229. """Get the scope name of runtime scope stack
  230. :param int stack_idx: The index of the runtime scope stack. Default is -1.
  231. 0 means the top level scope(the ``ROOT`` Scope),
  232. -1 means the current Scope,
  233. -2 means the scope used before entering the current scope, ...
  234. :return: Returns the scope name with the index, and returns ``None`` when occurs index error
  235. """
  236. try:
  237. return get_current_session().get_scope_name(stack_idx)
  238. except IndexError:
  239. logger.exception("Scope stack index error")
  240. return None
  241. def clear(scope=None):
  242. """Clear the content of the specified scope
  243. :param str scope: Target scope name. Default is the current scope.
  244. """
  245. if scope is None:
  246. scope = get_scope()
  247. send_msg('output_ctl', dict(clear=scope2dom(scope)))
  248. def remove(scope=None):
  249. """Remove the specified scope
  250. :param str scope: Target scope name. Default is the current scope.
  251. """
  252. if scope is None:
  253. scope = get_scope()
  254. assert scope != 'ROOT', "Can not remove `ROOT` scope."
  255. send_msg('output_ctl', dict(remove=scope2dom(scope)))
  256. def scroll_to(scope=None, position=Position.TOP):
  257. """
  258. Scroll the page to the specified scope
  259. :param str scope: Target scope. Default is the current scope.
  260. :param str position: Where to place the scope in the visible area of the page. Available value:
  261. * ``'top'`` : Keep the scope at the top of the visible area of the page
  262. * ``'middle'`` : Keep the scope at the middle of the visible area of the page
  263. * ``'bottom'`` : Keep the scope at the bottom of the visible area of the page
  264. """
  265. if scope is None:
  266. scope = get_scope()
  267. send_msg('output_ctl', dict(scroll_to=scope2dom(scope), position=position))
  268. def _get_output_spec(type, scope, position, **other_spec):
  269. """
  270. get the spec dict of output functions
  271. :param str type: output type
  272. :param str scope: target scope
  273. :param int position:
  274. :param other_spec: Additional output parameters, the None value will not be included in the return value
  275. :return dict: ``spec`` field of ``output`` command
  276. """
  277. spec = dict(type=type)
  278. # add non-None arguments to spec
  279. spec.update({k: v for k, v in other_spec.items() if v is not None})
  280. if not scope:
  281. scope_name = get_scope()
  282. else:
  283. scope_name = scope
  284. spec['scope'] = scope2dom(scope_name)
  285. spec['position'] = position
  286. return spec
  287. def put_text(*texts, sep=' ', inline=False, scope=None, position=OutputPosition.BOTTOM) -> Output:
  288. """
  289. Output plain text
  290. :param texts: Texts need to output. The type can be any object, and the `str()` function will be used for non-string objects.
  291. :param str sep: The separator between the texts
  292. :param bool inline: Use text as an inline element (no line break at the end of the text). Default is ``False``
  293. :param str scope: The target scope to output. If the scope does not exist, no operation will be performed.
  294. Can specify the scope name or use a integer to index the runtime scope stack.
  295. :param int position: The position where the content is output in target scope
  296. For more information about ``scope`` and ``position`` parameter, please refer to :ref:`User Manual <scope_param>`
  297. """
  298. content = sep.join(str(i) for i in texts)
  299. spec = _get_output_spec('text', content=content, inline=inline, scope=scope, position=position)
  300. return Output(spec)
  301. def _put_message(color, contents, closable=False, scope=None, position=OutputPosition.BOTTOM) -> Output:
  302. tpl = r"""
  303. <div class="alert alert-{{color}} {{#dismissible}}alert-dismissible fade show{{/dismissible}}" role="alert">
  304. {{#contents}}
  305. {{& pywebio_output_parse}}
  306. {{/contents}}
  307. {{#dismissible}}
  308. <button type="button" class="close" data-dismiss="alert" aria-label="Close">
  309. <span aria-hidden="true">&times;</span>
  310. </button>
  311. {{/dismissible}}
  312. </div>""".strip()
  313. contents = [c if isinstance(c, Output) else put_text(c) for c in contents]
  314. return put_widget(template=tpl, data=dict(color=color, contents=contents, dismissible=closable),
  315. scope=scope, position=position).enable_context_manager()
  316. def put_info(*contents, closable=False, scope=None, position=OutputPosition.BOTTOM) -> Output:
  317. """Output information message.
  318. :param contents: Message contents.
  319. The item is ``put_xxx()`` call, and any other type will be converted to ``put_text(content)``.
  320. :param bool closable: Whether to show a dismiss button on the right of the message.
  321. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  322. .. versionadded:: 1.2
  323. """
  324. return _put_message(color='info', contents=contents, closable=closable, scope=scope, position=position)
  325. def put_success(*contents, closable=False, scope=None, position=OutputPosition.BOTTOM) -> Output:
  326. """Output success message.
  327. .. seealso:: `put_info()`
  328. .. versionadded:: 1.2
  329. """
  330. return _put_message(color='success', contents=contents, closable=closable, scope=scope, position=position)
  331. def put_warning(*contents, closable=False, scope=None, position=OutputPosition.BOTTOM) -> Output:
  332. """Output warning message.
  333. .. seealso:: `put_info()`
  334. """
  335. return _put_message(color='warning', contents=contents, closable=closable, scope=scope, position=position)
  336. def put_error(*contents, closable=False, scope=None, position=OutputPosition.BOTTOM) -> Output:
  337. """Output error message.
  338. .. seealso:: `put_info()`
  339. """
  340. return _put_message(color='danger', contents=contents, closable=closable, scope=scope, position=position)
  341. def put_html(html, sanitize=False, scope=None, position=OutputPosition.BOTTOM) -> Output:
  342. """
  343. Output HTML content
  344. :param html: html string
  345. :param bool sanitize: Whether to use `DOMPurify <https://github.com/cure53/DOMPurify>`_ to filter the content to prevent XSS attacks.
  346. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  347. """
  348. # Compatible with ipython rich output
  349. # See: https://ipython.readthedocs.io/en/stable/config/integrating.html?highlight=Rich%20display#rich-display
  350. if hasattr(html, '__html__'):
  351. html = html.__html__()
  352. elif hasattr(html, '_repr_html_'):
  353. html = html._repr_html_()
  354. spec = _get_output_spec('html', content=html, sanitize=sanitize, scope=scope, position=position)
  355. return Output(spec)
  356. def put_code(content, language='', rows=None, scope=None, position=OutputPosition.BOTTOM) -> Output:
  357. """
  358. Output code block
  359. :param str content: code string
  360. :param str language: language of code
  361. :param int rows: The max lines of code can be displayed, no limit by default. The scroll bar will be displayed when the content exceeds.
  362. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  363. """
  364. if not isinstance(content, str):
  365. content = str(content)
  366. # For fenced code blocks, escaping the backtick need to use more backticks
  367. backticks = '```'
  368. while backticks in content:
  369. backticks += '`'
  370. code = "%s%s\n%s\n%s" % (backticks, language, content, backticks)
  371. out = put_markdown(code, scope=scope, position=position)
  372. if rows is not None:
  373. max_height = rows * 19 + 32 # 32 is the code css padding
  374. out.style("max-height: %spx" % max_height)
  375. return out
  376. def put_markdown(mdcontent, strip_indent=0, lstrip=False, options=None, sanitize=True,
  377. scope=None, position=OutputPosition.BOTTOM) -> Output:
  378. """
  379. Output Markdown
  380. :param str mdcontent: Markdown string
  381. :param int strip_indent: For each line of ``mdcontent``, if the first ``strip_indent`` characters are spaces, remove them
  382. :param bool lstrip: Whether to remove the whitespace at the beginning of each line of ``mdcontent``
  383. :param dict options: Configuration when parsing Markdown.
  384. PyWebIO uses `marked <https://marked.js.org/>`_ library to parse Markdown,
  385. the parse options see: https://marked.js.org/using_advanced#options (Only supports members of string and boolean type)
  386. :param bool sanitize: Whether to use `DOMPurify <https://github.com/cure53/DOMPurify>`_ to filter the content to prevent XSS attacks.
  387. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  388. When using Python triple quotes syntax to output multi-line Markdown in a function,
  389. if you indent the Markdown text, you can use ``strip_indent`` or ``lstrip`` to prevent Markdown from parsing errors
  390. (But do not use ``strip_indent`` and ``lstrip`` at the same time)::
  391. # It is ugly without strip_indent or lstrip
  392. def hello():
  393. put_markdown(r\""" # H1
  394. This is content.
  395. \""")
  396. # Using lstrip to get beautiful indent
  397. def hello():
  398. put_markdown(r\""" # H1
  399. This is content.
  400. \""", lstrip=True)
  401. # Using strip_indent to get beautiful indent
  402. def hello():
  403. put_markdown(r\""" # H1
  404. This is content.
  405. \""", strip_indent=4)
  406. """
  407. if strip_indent:
  408. lines = (
  409. i[strip_indent:] if (i[:strip_indent] == ' ' * strip_indent) else i
  410. for i in mdcontent.splitlines()
  411. )
  412. mdcontent = '\n'.join(lines)
  413. if lstrip:
  414. lines = (i.lstrip() for i in mdcontent.splitlines())
  415. mdcontent = '\n'.join(lines)
  416. spec = _get_output_spec('markdown', content=mdcontent, options=options, sanitize=sanitize,
  417. scope=scope, position=position)
  418. return Output(spec)
  419. class span_:
  420. def __init__(self, content, row=1, col=1):
  421. self.content, self.row, self.col = content, row, col
  422. @safely_destruct_output_when_exp('content')
  423. def span(content, row=1, col=1):
  424. """Create cross-cell content in :func:`put_table()` and :func:`put_grid()`
  425. :param content: cell content. It can be a string or ``put_xxx()`` call.
  426. :param int row: Vertical span, that is, the number of spanning rows
  427. :param int col: Horizontal span, that is, the number of spanning columns
  428. :Example:
  429. .. exportable-codeblock::
  430. :name: span
  431. :summary: Create cross-cell content with `span()`
  432. put_table([
  433. ['C'],
  434. [span('E', col=2)], # 'E' across 2 columns
  435. ], header=[span('A', row=2), 'B']) # 'A' across 2 rows
  436. put_grid([
  437. [put_text('A'), put_text('B')],
  438. [span(put_text('A'), col=2)], # 'A' across 2 columns
  439. ])
  440. """
  441. return span_(content, row, col)
  442. @safely_destruct_output_when_exp('tdata')
  443. def put_table(tdata, header=None, scope=None, position=OutputPosition.BOTTOM) -> Output:
  444. """
  445. Output table
  446. :param list tdata: Table data, which can be a two-dimensional list or a list of dict.
  447. The table cell can be a string or ``put_xxx()`` call. The cell can use the :func:`span()` to set the cell span.
  448. :param list header: Table header.
  449. When the item of ``tdata`` is of type ``list``, if the ``header`` parameter is omitted,
  450. the first item of ``tdata`` will be used as the header.
  451. The header item can also use the :func:`span()` function to set the cell span.
  452. When ``tdata`` is list of dict, ``header`` is used to specify the order of table headers, which cannot be omitted.
  453. In this case, the ``header`` can be a list of dict key or a list of ``(<label>, <dict key>)``.
  454. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  455. Example:
  456. .. exportable-codeblock::
  457. :name: put_table
  458. :summary: Output table with `put_table()`
  459. # 'Name' cell across 2 rows, 'Address' cell across 2 columns
  460. put_table([
  461. [span('Name',row=2), span('Address', col=2)],
  462. ['City', 'Country'],
  463. ['Wang', 'Beijing', 'China'],
  464. ['Liu', 'New York', 'America'],
  465. ])
  466. ## ----
  467. # Use `put_xxx()` in `put_table()`
  468. put_table([
  469. ['Type', 'Content'],
  470. ['html', put_html('X<sup>2</sup>')],
  471. ['text', '<hr/>'],
  472. ['buttons', put_buttons(['A', 'B'], onclick=...)], # ..doc-only
  473. ['buttons', put_buttons(['A', 'B'], onclick=put_text)], # ..demo-only
  474. ['markdown', put_markdown('`Awesome PyWebIO!`')],
  475. ['file', put_file('hello.text', b'hello world')],
  476. ['table', put_table([['A', 'B'], ['C', 'D']])]
  477. ])
  478. ## ----
  479. # Set table header
  480. put_table([
  481. ['Wang', 'M', 'China'],
  482. ['Liu', 'W', 'America'],
  483. ], header=['Name', 'Gender', 'Address'])
  484. ## ----
  485. # When ``tdata`` is list of dict
  486. put_table([
  487. {"Course":"OS", "Score": "80"},
  488. {"Course":"DB", "Score": "93"},
  489. ], header=["Course", "Score"]) # or header=[(put_markdown("*Course*"), "Course"), (put_markdown("*Score*") ,"Score")]
  490. .. versionadded:: 0.3
  491. The cell of table support ``put_xxx()`` calls.
  492. """
  493. # Change ``dict`` row table to list row table
  494. if tdata and isinstance(tdata[0], dict):
  495. if isinstance(header[0], (list, tuple)):
  496. header_ = [h[0] for h in header]
  497. order = [h[-1] for h in header]
  498. else:
  499. header_ = order = header
  500. tdata = [
  501. [row.get(k, '') for k in order]
  502. for row in tdata
  503. ]
  504. header = header_
  505. else:
  506. tdata = [list(i) for i in tdata] # copy data
  507. if header:
  508. tdata = [header, *tdata]
  509. span = {}
  510. for x in range(len(tdata)):
  511. for y in range(len(tdata[x])):
  512. cell = tdata[x][y]
  513. if isinstance(cell, span_):
  514. tdata[x][y] = cell.content
  515. span['%s,%s' % (x, y)] = dict(col=cell.col, row=cell.row)
  516. elif not isinstance(cell, Output):
  517. tdata[x][y] = str(cell)
  518. spec = _get_output_spec('table', data=tdata, span=span, scope=scope, position=position)
  519. return Output(spec)
  520. def _format_button(buttons):
  521. """
  522. Format `buttons` parameter in `put_buttons()`
  523. :param buttons:
  524. {label:, value:, }
  525. (label, value, )
  526. single value, label=value
  527. :return: [{value:, label:, }, ...]
  528. """
  529. btns = []
  530. for btn in buttons:
  531. if isinstance(btn, Mapping):
  532. assert 'value' in btn and 'label' in btn, 'actions item must have value and label key'
  533. elif isinstance(btn, (list, tuple)):
  534. assert len(btn) == 2, 'actions item format error'
  535. btn = dict(zip(('label', 'value'), btn))
  536. else:
  537. btn = dict(value=btn, label=btn)
  538. btns.append(btn)
  539. return btns
  540. def put_buttons(buttons, onclick, small=None, link_style=False, outline=False, group=False, scope=None,
  541. position=OutputPosition.BOTTOM, **callback_options) -> Output:
  542. """
  543. Output a group of buttons and bind click event
  544. :param list buttons: Button list. The available formats of list items are:
  545. * dict: ``{label:(str)button label, value:(str)button value, color:(str, optional)button color}``
  546. * tuple or list: ``(label, value)``
  547. * single value: label and value of option use the same value
  548. The ``value`` of button can be any JSON serializable object.
  549. The ``color`` of button can be one of: `primary`, `secondary`, `success`, `danger`, `warning`, `info`, `light`, `dark`.
  550. Example:
  551. .. exportable-codeblock::
  552. :name: put_buttons-btn_class
  553. :summary: `put_buttons()`
  554. put_buttons([dict(label='success', value='s', color='success')], onclick=...) # ..doc-only
  555. put_buttons([ # ..demo-only
  556. dict(label=i, value=i, color=i) # ..demo-only
  557. for i in ['primary', 'secondary', 'success', 'danger', 'warning', 'info', 'light', 'dark'] # ..demo-only
  558. ], onclick=put_text) # ..demo-only
  559. :type onclick: callable / list
  560. :param onclick: Callback which will be called when button is clicked. ``onclick`` can be a callable object or a list of it.
  561. If ``onclick`` is callable object, its signature is ``onclick(btn_value)``. ``btn_value`` is ``value`` of the button that is clicked.
  562. If ``onclick`` is a list, the item receives no parameter. In this case, each item in the list corresponds to the buttons one-to-one.
  563. Tip: You can use ``functools.partial`` to save more context information in ``onclick``.
  564. Note: When in :ref:`Coroutine-based session <coroutine_based_session>`, the callback can be a coroutine function.
  565. :param bool small: Whether to use small size button. Default is False.
  566. :param bool link_style: Whether to use link style button. Default is False
  567. :param bool outline: Whether to use outline style button. Default is False
  568. :param bool group: Whether to group the buttons together. Default is False
  569. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  570. :param callback_options: Other options of the ``onclick`` callback. There are different options according to the session implementation
  571. When in Coroutine-based Session:
  572. * mutex_mode: Default is ``False``. If set to ``True``, new click event will be ignored when the current callback is running.
  573. This option is available only when ``onclick`` is a coroutine function.
  574. When in Thread-based Session:
  575. * serial_mode: Default is ``False``, and every time a callback is triggered,
  576. the callback function will be executed immediately in a new thread.
  577. If set ``serial_mode`` to ``True``
  578. After enabling serial_mode, the button's callback will be executed serially in a resident thread in the session,
  579. and all other new click event callbacks (including the ``serial_mode=False`` callback) will be queued for
  580. the current click event to complete. If the callback function runs for a short time,
  581. you can turn on ``serial_mode`` to improve performance.
  582. Example:
  583. .. exportable-codeblock::
  584. :name: put_buttons
  585. :summary: `put_buttons()` usage
  586. from functools import partial
  587. def row_action(choice, id):
  588. put_text("You click %s button with id: %s" % (choice, id))
  589. put_buttons(['edit', 'delete'], onclick=partial(row_action, id=1))
  590. ## ----
  591. def edit():
  592. put_text("You click edit button")
  593. def delete():
  594. put_text("You click delete button")
  595. put_buttons(['edit', 'delete'], onclick=[edit, delete])
  596. """
  597. btns = _format_button(buttons)
  598. if isinstance(onclick, Sequence):
  599. assert len(btns) == len(onclick), "`onclick` and `buttons` must be same length."
  600. onclick = {btn['value']: callback for btn, callback in zip(btns, onclick)}
  601. def click_callback(btn_val):
  602. if isinstance(onclick, dict):
  603. return onclick[btn_val]()
  604. else:
  605. return onclick(btn_val)
  606. callback_id = output_register_callback(click_callback, **callback_options)
  607. spec = _get_output_spec('buttons', callback_id=callback_id, buttons=btns, small=small,
  608. scope=scope, position=position, link=link_style, outline=outline, group=group)
  609. return Output(spec)
  610. def put_button(label, onclick, color=None, small=None, link_style=False, outline=False, scope=None,
  611. position=OutputPosition.BOTTOM) -> Output:
  612. """Output a single button and bind click event to it.
  613. :param str label: Button label
  614. :param callable onclick: Callback which will be called when button is clicked.
  615. :param str color: The color of the button,
  616. can be one of: `primary`, `secondary`, `success`, `danger`, `warning`, `info`, `light`, `dark`.
  617. :param - small, link_style, outline, scope, position: Those arguments have the same meaning as for `put_buttons()`
  618. Example:
  619. .. exportable-codeblock::
  620. :name: put_button
  621. :summary: `put_button()` usage
  622. put_button("click me", onclick=lambda: toast("Clicked"), color='success', outline=True)
  623. .. versionadded:: 1.4
  624. """
  625. return put_buttons([{'label': label, 'value': '', 'color': color or 'primary'}], onclick=[onclick],
  626. small=small, link_style=link_style, outline=outline, scope=scope, position=position)
  627. def put_image(src, format=None, title='', width=None, height=None,
  628. scope=None, position=OutputPosition.BOTTOM) -> Output:
  629. """Output image
  630. :param src: Source of image. It can be a string specifying image URL, a bytes-like object specifying
  631. the binary content of an image or an instance of ``PIL.Image.Image``
  632. :param str title: Image description.
  633. :param str width: The width of image. It can be CSS pixels (like `'30px'`) or percentage (like `'10%'`).
  634. :param str height: The height of image. It can be CSS pixels (like `'30px'`) or percentage (like `'10%'`).
  635. If only one value of ``width`` and ``height`` is specified, the browser will scale image according to its original size.
  636. :param str format: Image format, optinoal. e.g.: ``png``, ``jpeg``, ``gif``, etc. Only available when `src` is non-URL
  637. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  638. Example:
  639. .. exportable-codeblock::
  640. :name: put_image
  641. :summary: `put_image()` usage
  642. from pywebio import STATIC_PATH # ..demo-only
  643. img = open(STATIC_PATH + '/image/favicon_open_32.png', 'rb').read() # ..demo-only
  644. img = open('/path/to/some/image.png', 'rb').read() # ..doc-only
  645. put_image(img, width='50px')
  646. ## ----
  647. put_image('https://www.python.org/static/img/python-logo.png')
  648. """
  649. if isinstance(src, PILImage):
  650. format = format or src.format or 'JPEG'
  651. imgByteArr = io.BytesIO()
  652. src.save(imgByteArr, format=format)
  653. src = imgByteArr.getvalue()
  654. if isinstance(src, (bytes, bytearray)):
  655. b64content = b64encode(src).decode('ascii')
  656. format = '' if format is None else ('image/%s' % format)
  657. format = html.escape(format, quote=True)
  658. src = "data:{format};base64, {b64content}".format(format=format, b64content=b64content)
  659. width = 'width="%s"' % html.escape(width, quote=True) if width is not None else ''
  660. height = 'height="%s"' % html.escape(height, quote=True) if height is not None else ''
  661. tag = r'<img src="{src}" alt="{title}" {width} {height}/>'.format(src=src, title=html.escape(title, quote=True),
  662. height=height, width=width)
  663. return put_html(tag, scope=scope, position=position)
  664. def put_file(name, content, label=None, scope=None, position=OutputPosition.BOTTOM) -> Output:
  665. """Output a link to download a file
  666. To show a link with the file name on the browser. When click the link, the browser automatically downloads the file.
  667. :param str name: File name downloaded as
  668. :param content: File content. It is a bytes-like object
  669. :param str label: The label of the download link, which is the same as the file name by default.
  670. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  671. Example:
  672. .. exportable-codeblock::
  673. :name: put_file
  674. :summary: `put_file()` usage
  675. content = open('./some-file', 'rb').read() # ..doc-only
  676. content = open('README.md', 'rb').read() # ..demo-only
  677. put_file('hello-world.txt', content, 'download me')
  678. """
  679. if label is None:
  680. label = name
  681. output = put_buttons(buttons=[label], link_style=True,
  682. onclick=[lambda: download(name, content)],
  683. scope=scope, position=position)
  684. return output
  685. def put_link(name, url=None, app=None, new_window=False, scope=None,
  686. position=OutputPosition.BOTTOM) -> Output:
  687. """Output hyperlinks to other web page or PyWebIO Application page.
  688. :param str name: The label of the link
  689. :param str url: Target url
  690. :param str app: Target PyWebIO Application name. See also: :ref:`Server mode <server_and_script_mode>`
  691. :param bool new_window: Whether to open the link in a new window
  692. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  693. The ``url`` and ``app`` parameters must specify one but not both
  694. """
  695. assert bool(url is None) != bool(app is None), "Must set `url` or `app` parameter but not both"
  696. href = 'javascript:WebIO.openApp(%r, %d)' % (app, new_window) if app is not None else url
  697. target = '_blank' if (new_window and url) else '_self'
  698. tag = '<a href="{href}" target="{target}">{name}</a>'.format(
  699. href=html.escape(href, quote=True), target=target, name=html.escape(name))
  700. return put_html(tag, scope=scope, position=position)
  701. def put_processbar(name, init=0, label=None, auto_close=False, scope=None,
  702. position=OutputPosition.BOTTOM) -> Output:
  703. """Output a process bar
  704. :param str name: The name of the progress bar, which is the unique identifier of the progress bar
  705. :param float init: The initial progress value of the progress bar. The value is between 0 and 1
  706. :param str label: The label of process bar. The default is the percentage value of the current progress.
  707. :param bool auto_close: Whether to remove the progress bar after the progress is completed
  708. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  709. Example:
  710. .. exportable-codeblock::
  711. :name: put_processbar
  712. :summary: `put_processbar()` usage
  713. import time
  714. put_processbar('bar');
  715. for i in range(1, 11):
  716. set_processbar('bar', i / 10)
  717. time.sleep(0.1)
  718. """
  719. processbar_id = 'webio-processbar-%s' % name
  720. percentage = init * 100
  721. label = '%.1f%%' % percentage if label is None else label
  722. tpl = """<div class="progress" style="margin-top: 4px;">
  723. <div id="{{elem_id}}" class="progress-bar bg-info progress-bar-striped progress-bar-animated" role="progressbar"
  724. style="width: {{percentage}}%;" aria-valuenow="{{init}}" aria-valuemin="0" aria-valuemax="1" data-auto-close="{{auto_close}}">{{label}}
  725. </div>
  726. </div>"""
  727. return put_widget(tpl, data=dict(elem_id=processbar_id, init=init, label=label,
  728. percentage=percentage, auto_close=int(bool(auto_close))), scope=scope,
  729. position=position)
  730. def set_processbar(name, value, label=None):
  731. """Set the progress of progress bar
  732. :param str name: The name of the progress bar
  733. :param float value: The progress value of the progress bar. The value is between 0 and 1
  734. :param str label: The label of process bar. The default is the percentage value of the current progress.
  735. See also: `put_processbar()`
  736. """
  737. from pywebio.session import run_js
  738. processbar_id = 'webio-processbar-%s' % name
  739. percentage = value * 100
  740. label = '%.1f%%' % percentage if label is None else label
  741. js_code = """
  742. let bar = $("#{processbar_id}");
  743. bar[0].style.width = "{percentage}%";
  744. bar.attr("aria-valuenow", "{value}");
  745. bar.text({label!r});
  746. """.format(processbar_id=processbar_id, percentage=percentage, value=value, label=label)
  747. if value == 1:
  748. js_code += "if(bar.data('autoClose')=='1')bar.parent().remove();"
  749. run_js(js_code)
  750. def put_loading(shape='border', color='dark', scope=None, position=OutputPosition.BOTTOM) -> Output:
  751. """Output loading prompt
  752. :param str shape: The shape of loading prompt. The available values are: `'border'` (default)、 `'grow'`
  753. :param str color: The color of loading prompt. The available values are: `'primary'` 、 `'secondary'` 、
  754. `'success'` 、 `'danger'` 、 `'warning'` 、`'info'` 、`'light'` 、 `'dark'` (default)
  755. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  756. `put_loading()` can be used in 2 ways: direct call and context manager:
  757. .. exportable-codeblock::
  758. :name: put_loading
  759. :summary: `put_loading()` usage
  760. for shape in ('border', 'grow'):
  761. for color in ('primary', 'secondary', 'success', 'danger', 'warning', 'info', 'light', 'dark'):
  762. put_text(shape, color)
  763. put_loading(shape=shape, color=color)
  764. ## ----
  765. import time # ..demo-only
  766. # Use as context manager, the loading prompt will disappear automatically when the context block exits.
  767. with put_loading():
  768. time.sleep(3) # Some time-consuming operations
  769. put_text("The answer of the universe is 42")
  770. ## ----
  771. # using style() to set the size of the loading prompt
  772. put_loading().style('width:4rem; height:4rem')
  773. """
  774. assert shape in ('border', 'grow'), "shape must in ('border', 'grow')"
  775. assert color in {'primary', 'secondary', 'success', 'danger', 'warning', 'info', 'light', 'dark'}
  776. html = """<div class="spinner-{shape} text-{color}" role="status">
  777. <span class="sr-only">Loading...</span>
  778. </div>""".format(shape=shape, color=color)
  779. scope_name = random_str(10)
  780. def enter(self):
  781. self.spec['container_dom_id'] = scope2dom(scope_name, no_css_selector=True)
  782. self.send()
  783. return scope_name
  784. def exit_(self, exc_type, exc_val, exc_tb):
  785. remove(scope_name)
  786. return False # Propagate Exception
  787. return put_html(html, sanitize=False, scope=scope, position=position). \
  788. enable_context_manager(custom_enter=enter, custom_exit=exit_)
  789. @safely_destruct_output_when_exp('content')
  790. def put_collapse(title, content=[], open=False, scope=None, position=OutputPosition.BOTTOM) -> Output:
  791. """Output collapsible content
  792. :param str title: Title of content
  793. :type content: list/str/put_xxx()
  794. :param content: The content can be a string, the ``put_xxx()`` calls , or a list of them.
  795. :param bool open: Whether to expand the content. Default is ``False``.
  796. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  797. Example:
  798. .. exportable-codeblock::
  799. :name: put_collapse
  800. :summary: `put_collapse()` usage
  801. put_collapse('Collapse title', [
  802. 'text',
  803. put_markdown('~~Strikethrough~~'),
  804. put_table([
  805. ['Commodity', 'Price'],
  806. ['Apple', '5.5'],
  807. ])
  808. ], open=True)
  809. ## ----
  810. put_collapse('Large text', 'Awesome PyWebIO! '*30)
  811. """
  812. if not isinstance(content, (list, tuple, OutputList)):
  813. content = [content]
  814. for item in content:
  815. assert isinstance(item, (str, Output)), "put_collapse() content must be list of str/put_xxx()"
  816. tpl = """<details {{#open}}open{{/open}}>
  817. <summary>{{title}}</summary>
  818. {{#contents}}
  819. {{& pywebio_output_parse}}
  820. {{/contents}}
  821. </details>"""
  822. return put_widget(tpl, dict(title=title, contents=content, open=open), scope=scope,
  823. position=position).enable_context_manager()
  824. @safely_destruct_output_when_exp('content')
  825. def put_scrollable(content=[], height=400, keep_bottom=False, horizon_scroll=False, border=True,
  826. scope=None, position=OutputPosition.BOTTOM, **kwargs) -> Output:
  827. """Output a fixed height content area. scroll bar is displayed when the content exceeds the limit
  828. :type content: list/str/put_xxx()
  829. :param content: The content can be a string, the ``put_xxx()`` calls , or a list of them.
  830. :param int/tuple height: The height of the area (in pixels).
  831. ``height`` parameter also accepts ``(min_height, max_height)`` to indicate the range of height, for example,
  832. ``(100, 200)`` means that the area has a minimum height of 100 pixels and a maximum of 200 pixels.
  833. :param bool horizon_scroll: Whether to use the horizontal scroll bar
  834. :param bool border: Whether to show border
  835. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  836. Example:
  837. .. exportable-codeblock::
  838. :name: put_scrollable
  839. :summary: `put_scrollable()` usage
  840. import time
  841. o = output("You can click the area to prevent auto scroll.")
  842. put_scrollable(o, height=200, keep_bottom=True)
  843. while 1:
  844. o.append(time.time())
  845. time.sleep(0.5)
  846. .. versionchanged:: 1.1
  847. add ``height`` parameter,remove ``max_height`` parameter;
  848. add ``keep_bottom`` parameter
  849. """
  850. if not isinstance(content, (list, tuple, OutputList)):
  851. content = [content]
  852. content = [i if isinstance(i, Output) else put_text(i) for i in content]
  853. if 'max_height' in kwargs:
  854. import warnings
  855. warnings.warn("`max_height` parameter is deprecated in `put_scrollable()`, use `height` instead.",
  856. DeprecationWarning, stacklevel=3)
  857. height = kwargs['max_height'] # Backward compatible
  858. try:
  859. min_height, max_height = height
  860. except Exception:
  861. min_height, max_height = height, height
  862. dom_id = 'pywebio-%s' % random_str(10)
  863. tpl = """<div id="{{dom_id}}" {{#keep_bottom}}tabindex="0"{{/keep_bottom}}
  864. style="min-height: {{min_height}}px; max-height: {{max_height}}px;
  865. overflow-y: scroll;
  866. {{#horizon_scroll}}overflow-x: scroll;{{/horizon_scroll}}
  867. {{#border}}
  868. border: 1px solid rgba(0,0,0,.125);
  869. box-shadow: inset 0 0 2px 0 rgba(0,0,0,.1);
  870. {{/border}}
  871. padding: 10px;
  872. margin-bottom: 10px;">
  873. {{#contents}}
  874. {{& pywebio_output_parse}}
  875. {{/contents}}
  876. </div>"""
  877. if keep_bottom:
  878. tpl += """
  879. <script>
  880. (function(){
  881. let div = document.getElementById(%r), stop=false;
  882. $(div).on('focusin', function(e){ stop=true }).on('focusout', function(e){ stop=false });;
  883. new MutationObserver(function (mutations, observe) {
  884. if(!stop) $(div).stop().animate({ scrollTop: $(div).prop("scrollHeight")}, 200);
  885. }).observe(div, { childList: true, subtree:true });
  886. })();
  887. </script>
  888. """ % dom_id
  889. return put_widget(template=tpl,
  890. data=dict(dom_id=dom_id, contents=content, min_height=min_height,
  891. max_height=max_height, keep_bottom=keep_bottom,
  892. horizon_scroll=horizon_scroll, border=border),
  893. scope=scope, position=position).enable_context_manager()
  894. @safely_destruct_output_when_exp('tabs')
  895. def put_tabs(tabs, scope=None, position=OutputPosition.BOTTOM) -> Output:
  896. """Output tabs.
  897. :param list tabs: Tab list, each item is a dict: ``{"title": "Title", "content": ...}`` .
  898. The ``content`` can be a string, the ``put_xxx()`` calls , or a list of them.
  899. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  900. .. exportable-codeblock::
  901. :name: put_tabs
  902. :summary: `put_tabs()` usage
  903. put_tabs([
  904. {'title': 'Text', 'content': 'Hello world'},
  905. {'title': 'Markdown', 'content': put_markdown('~~Strikethrough~~')},
  906. {'title': 'More content', 'content': [
  907. put_table([
  908. ['Commodity', 'Price'],
  909. ['Apple', '5.5'],
  910. ['Banana', '7'],
  911. ]),
  912. put_link('pywebio', 'https://github.com/wang0618/PyWebIO')
  913. ]},
  914. ])
  915. .. versionadded:: 1.3
  916. """
  917. for tab in tabs:
  918. assert 'title' in tab and 'content' in tab
  919. spec = _get_output_spec('tabs', tabs=tabs, scope=scope, position=position)
  920. return Output(spec)
  921. @safely_destruct_output_when_exp('data')
  922. def put_widget(template, data, scope=None, position=OutputPosition.BOTTOM) -> Output:
  923. """Output your own widget
  924. :param template: html template, using `mustache.js <https://github.com/janl/mustache.js>`_ syntax
  925. :param dict data: Data used to render the template.
  926. The data can include the ``put_xxx()`` calls, and the JS function ``pywebio_output_parse`` can be used to
  927. parse the content of ``put_xxx()``. For string input, ``pywebio_output_parse`` will parse into text.
  928. ⚠️:When using the ``pywebio_output_parse`` function, you need to turn off the html escaping of mustache:
  929. ``{{& pywebio_output_parse}}``, see the example below.
  930. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  931. :Example:
  932. .. exportable-codeblock::
  933. :name: put_widget
  934. :summary: Use `put_widget()` to output your own widget
  935. tpl = '''
  936. <details {{#open}}open{{/open}}>
  937. <summary>{{title}}</summary>
  938. {{#contents}}
  939. {{& pywebio_output_parse}}
  940. {{/contents}}
  941. </details>
  942. '''
  943. put_widget(tpl, {
  944. "open": True,
  945. "title": 'More content',
  946. "contents": [
  947. 'text',
  948. put_markdown('~~Strikethrough~~'),
  949. put_table([
  950. ['Commodity', 'Price'],
  951. ['Apple', '5.5'],
  952. ['Banana', '7'],
  953. ])
  954. ]
  955. })
  956. """
  957. spec = _get_output_spec('custom_widget', template=template, data=data, scope=scope, position=position)
  958. return Output(spec)
  959. @safely_destruct_output_when_exp('content')
  960. def put_row(content=[], size=None, scope=None, position=OutputPosition.BOTTOM) -> Output:
  961. """Use row layout to output content. The content is arranged horizontally
  962. :param list content: Content list, the item is ``put_xxx()`` call or ``None``. ``None`` represents the space between the output
  963. :param str size:
  964. | Used to indicate the width of the items, is a list of width values separated by space.
  965. | Each width value corresponds to the items one-to-one. (``None`` item should also correspond to a width value).
  966. | By default, ``size`` assigns a width of 10 pixels to the ``None`` item, and distributes the width equally to the remaining items.
  967. Available format of width value are:
  968. - pixels: like ``100px``
  969. - percentage: Indicates the percentage of available width. like ``33.33%``
  970. - ``fr`` keyword: Represents a scale relationship, 2fr represents twice the width of 1fr
  971. - ``auto`` keyword: Indicates that the length is determined by the browser
  972. - ``minmax(min, max)`` : Generate a length range, indicating that the length is within this range.
  973. It accepts two parameters, minimum and maximum.
  974. For example: ``minmax(100px, 1fr)`` means the length is not less than 100px and not more than 1fr
  975. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  976. :Example:
  977. .. exportable-codeblock::
  978. :name: put_row
  979. :summary: `put_row()` usage
  980. # Two code blocks of equal width, separated by 10 pixels
  981. put_row([put_code('A'), None, put_code('B')])
  982. ## ----
  983. # The width ratio of the left and right code blocks is 2:3, which is equivalent to size='2fr 10px 3fr'
  984. put_row([put_code('A'), None, put_code('B')], size='40% 10px 60%')
  985. """
  986. return _row_column_layout(content, flow='column', size=size, scope=scope,
  987. position=position).enable_context_manager()
  988. @safely_destruct_output_when_exp('content')
  989. def put_column(content=[], size=None, scope=None, position=OutputPosition.BOTTOM) -> Output:
  990. """Use column layout to output content. The content is arranged vertically
  991. :param list content: Content list, the item is ``put_xxx()`` call or ``None``. ``None`` represents the space between the output
  992. :param str size: Used to indicate the width of the items, is a list of width values separated by space.
  993. The format is the same as the ``size`` parameter of the `put_row()` function.
  994. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  995. """
  996. return _row_column_layout(content, flow='row', size=size, scope=scope, position=position).enable_context_manager()
  997. def _row_column_layout(content, flow, size, scope=None, position=OutputPosition.BOTTOM) -> Output:
  998. if not isinstance(content, (list, tuple, OutputList)):
  999. content = [content]
  1000. if not size:
  1001. size = ' '.join('1fr' if c is not None else '10px' for c in content)
  1002. content = [c if c is not None else put_html('<div></div>') for c in content]
  1003. for item in content:
  1004. assert isinstance(item, Output), "put_row()/put_column()'s content must be list of put_xxx()"
  1005. style = 'grid-auto-flow: {flow}; grid-template-{flow}s: {size};'.format(flow=flow, size=size)
  1006. tpl = """
  1007. <div style="display: grid; %s">
  1008. {{#contents}}
  1009. {{& pywebio_output_parse}}
  1010. {{/contents}}
  1011. </div>""".strip() % html.escape(style, quote=True)
  1012. return put_widget(template=tpl, data=dict(contents=content), scope=scope,
  1013. position=position)
  1014. @safely_destruct_output_when_exp('content')
  1015. def put_grid(content, cell_width='auto', cell_height='auto', cell_widths=None, cell_heights=None, direction='row',
  1016. scope=None, position=OutputPosition.BOTTOM) -> Output:
  1017. """Output content using grid layout
  1018. :param content: Content of grid, which is a two-dimensional list. The item of list is ``put_xxx()`` call or ``None``.
  1019. ``None`` represents the space between the output. The item can use the `span()` to set the cell span.
  1020. :param str cell_width: The width of grid cell.
  1021. :param str cell_height: The height of grid cell.
  1022. :param str cell_widths: The width of each column of the grid. The width values are separated by a space.
  1023. Can not use ``cell_widths`` and ``cell_width`` at the same time
  1024. :param str cell_heights: The height of each row of the grid. The height values are separated by a space.
  1025. Can not use ``cell_heights`` and ``cell_height`` at the same time
  1026. :param str direction: Controls how auto-placed items get inserted in the grid.
  1027. Can be ``'row'``(default) or ``'column'`` .
  1028. | ``'row'`` : Places items by filling each row
  1029. | ``'column'`` : Places items by filling each column
  1030. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  1031. The format of width/height value in ``cell_width``,``cell_height``,``cell_widths``,``cell_heights``
  1032. can refer to the ``size`` parameter of the `put_row()` function.
  1033. :Example:
  1034. .. exportable-codeblock::
  1035. :name: put_grid
  1036. :summary: `put_grid()` usage
  1037. put_grid([
  1038. [put_text('A'), put_text('B'), put_text('C')],
  1039. [None, span(put_text('D'), col=2, row=1)],
  1040. [put_text('E'), put_text('F'), put_text('G')],
  1041. ], cell_width='100px', cell_height='100px')
  1042. """
  1043. assert direction in ('row', 'column'), '"direction" parameter must be "row" or "column"'
  1044. lens = [0] * len(content)
  1045. for x in range(len(content)):
  1046. for y in range(len(content[x])):
  1047. cell = content[x][y]
  1048. if isinstance(cell, span_):
  1049. for i in range(cell.row): lens[x + i] += cell.col
  1050. css = 'grid-row-start: span {row}; grid-column-start: span {col};'.format(row=cell.row, col=cell.col)
  1051. elem = put_html('<div></div>') if cell.content is None else cell.content
  1052. content[x][y] = elem.style(css)
  1053. else:
  1054. lens[x] += 1
  1055. if content[x][y] is None:
  1056. content[x][y] = put_html('<div></div>')
  1057. # 为长度不足的行添加空元素
  1058. # Add empty elements for rows with insufficient length
  1059. m = max(lens)
  1060. for idx, i in enumerate(content):
  1061. i.extend(put_html('<div></div>') for _ in range(m - lens[idx]))
  1062. row_cnt, col_cnt = len(content), m
  1063. if direction == 'column':
  1064. row_cnt, col_cnt = m, len(content)
  1065. if not cell_widths:
  1066. cell_widths = 'repeat({col_cnt},{cell_width})'.format(col_cnt=col_cnt, cell_width=cell_width)
  1067. if not cell_heights:
  1068. cell_heights = 'repeat({row_cnt},{cell_height})'.format(row_cnt=row_cnt, cell_height=cell_height)
  1069. css = ('grid-auto-flow: {flow};'
  1070. 'grid-template-columns: {cell_widths};'
  1071. 'grid-template-rows: {cell_heights};'
  1072. ).format(flow=direction, cell_heights=cell_heights, cell_widths=cell_widths)
  1073. tpl = """
  1074. <div style="display: grid; %s">
  1075. {{#contents}}
  1076. {{#.}}
  1077. {{& pywebio_output_parse}}
  1078. {{/.}}
  1079. {{/contents}}
  1080. </div>""".strip() % html.escape(css, quote=True)
  1081. return put_widget(template=tpl, data=dict(contents=content), scope=scope, position=position)
  1082. @safely_destruct_output_when_exp('content')
  1083. def put_scope(name, content=[], scope=None, position=OutputPosition.BOTTOM) -> Output:
  1084. """Output a scope
  1085. :param str name:
  1086. :param list/put_xxx() content: The initial content of the scope, can be ``put_xxx()`` or a list of it.
  1087. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  1088. """
  1089. if not isinstance(content, list):
  1090. content = [content]
  1091. assert is_html_safe_value(name), "Scope name only allow letter/digit/'_'/'-' char."
  1092. dom_id = scope2dom(name, no_css_selector=True)
  1093. spec = _get_output_spec('scope', dom_id=dom_id, contents=content, scope=scope, position=position)
  1094. return Output(spec)
  1095. @safely_destruct_output_when_exp('contents')
  1096. def output(*contents):
  1097. """Placeholder of output
  1098. .. deprecated:: 1.5
  1099. See :ref:`User Guide <put_scope>` for new way to set css style for output.
  1100. ``output()`` can be passed in anywhere that ``put_xxx()`` can passed in. A handler it returned by ``output()``,
  1101. and after being output, the content can also be modified by the handler (See code example below).
  1102. :param contents: The initial contents to be output.
  1103. The item is ``put_xxx()`` call, and any other type will be converted to ``put_text(content)``.
  1104. :return: An OutputHandler instance, the methods of the instance are as follows:
  1105. * ``reset(*contents)`` : Reset original contents to ``contents``
  1106. * ``append(*contents)`` : Append ``contents`` to original contents
  1107. * ``insert(idx, *contents)`` : insert ``contents`` into original contents.
  1108. | when idx>=0, the output content is inserted before the element of the ``idx`` index.
  1109. | when idx<0, the output content is inserted after the element of the ``idx`` index.
  1110. Among them, the parameter ``contents`` is the same as ``output()``.
  1111. :Example:
  1112. .. exportable-codeblock::
  1113. :name: output
  1114. :summary: `output()` usage
  1115. hobby = output(put_text('Coding')) # equal to output('Coding')
  1116. put_table([
  1117. ['Name', 'Hobbies'],
  1118. ['Wang', hobby] # hobby is initialized to Coding
  1119. ])
  1120. ## ----
  1121. hobby.reset('Movie') # hobby is reset to Movie
  1122. ## ----
  1123. hobby.append('Music', put_text('Drama')) # append Music, Drama to hobby
  1124. ## ----
  1125. hobby.insert(0, put_markdown('**Coding**')) # insert the Coding into the top of the hobby
  1126. """
  1127. import warnings
  1128. warnings.warn("`pywebio.output.output()` is deprecated since v1.5 and will remove in the future version, "
  1129. "use `pywebio.output.put_scope()` instead", DeprecationWarning, stacklevel=2)
  1130. class OutputHandler(Output):
  1131. """
  1132. 与 `Output` 的不同在于, 不会在销毁时(__del__)自动输出
  1133. The difference with `Output` is that `OutputHandler` will not automatically output when destroyed (__del__)
  1134. """
  1135. def __del__(self):
  1136. pass
  1137. def __init__(self, spec, scope):
  1138. super().__init__(spec)
  1139. self.scope = scope
  1140. @safely_destruct_output_when_exp('outputs')
  1141. def reset(self, *outputs):
  1142. clear_scope(scope=self.scope)
  1143. self.append(*outputs)
  1144. @safely_destruct_output_when_exp('outputs')
  1145. def append(self, *outputs):
  1146. for o in outputs:
  1147. if not isinstance(o, Output):
  1148. o = put_text(o)
  1149. o.spec['scope'] = scope2dom(self.scope)
  1150. o.spec['position'] = OutputPosition.BOTTOM
  1151. o.send()
  1152. @safely_destruct_output_when_exp('outputs')
  1153. def insert(self, idx, *outputs):
  1154. """
  1155. idx可为负
  1156. idx can be negative
  1157. """
  1158. direction = 1 if idx >= 0 else -1
  1159. for acc, o in enumerate(outputs):
  1160. if not isinstance(o, Output):
  1161. o = put_text(o)
  1162. o.spec['scope'] = scope2dom(self.scope)
  1163. o.spec['position'] = idx + direction * acc
  1164. o.send()
  1165. contents = [c if isinstance(c, Output) else put_text(c) for c in contents]
  1166. dom_name = random_str(10)
  1167. tpl = """<div class="{{dom_class_name}}">
  1168. {{#contents}}
  1169. {{#.}}
  1170. {{& pywebio_output_parse}}
  1171. {{/.}}
  1172. {{/contents}}
  1173. </div>"""
  1174. out_spec = put_widget(template=tpl,
  1175. data=dict(contents=contents, dom_class_name=scope2dom(dom_name, no_css_selector=True)))
  1176. return OutputHandler(Output.dump_dict(out_spec), ('.', dom_name))
  1177. @safely_destruct_output_when_exp('outputs')
  1178. def style(outputs, css_style) -> Union[Output, OutputList]:
  1179. """Customize the css style of output content
  1180. .. deprecated:: 1.3
  1181. See :ref:`User Guide <style>` for new way to set css style for output.
  1182. :param outputs: The output content can be a ``put_xxx()`` call or a list of it.
  1183. :type outputs: list/put_xxx()
  1184. :param str css_style: css style string
  1185. :return: The output contents with css style added:
  1186. Note: If ``outputs`` is a list of ``put_xxx()`` calls, the style will be set for each item of the list.
  1187. And the return value can be used in anywhere accept a list of ``put_xxx()`` calls.
  1188. :Example:
  1189. .. exportable-codeblock::
  1190. :name: style-deprecated
  1191. :summary: `style()` usage
  1192. style(put_text('Red'), 'color:red')
  1193. ## ----
  1194. style([
  1195. put_text('Red'),
  1196. put_markdown('~~del~~')
  1197. ], 'color:red')
  1198. ## ----
  1199. put_table([
  1200. ['A', 'B'],
  1201. ['C', style(put_text('Red'), 'color:red')],
  1202. ])
  1203. ## ----
  1204. put_collapse('title', style([
  1205. put_text('text'),
  1206. put_markdown('~~del~~'),
  1207. ], 'margin-left:20px'))
  1208. """
  1209. import warnings
  1210. warnings.warn("`pywebio.output.style()` is deprecated since v1.3 and will remove in the future version, "
  1211. "use `put_xxx(...).style(...)` instead", DeprecationWarning, stacklevel=2)
  1212. if not isinstance(outputs, (list, tuple, OutputList)):
  1213. ol = [outputs]
  1214. else:
  1215. ol = outputs
  1216. outputs = OutputList(outputs)
  1217. for o in ol:
  1218. assert isinstance(o, Output), 'style() only accept put_xxx() input'
  1219. o.spec.setdefault('style', '')
  1220. o.spec['style'] += ';%s' % css_style
  1221. return outputs
  1222. @safely_destruct_output_when_exp('content')
  1223. def popup(title, content=None, size=PopupSize.NORMAL, implicit_close=True, closable=True):
  1224. """
  1225. Show a popup.
  1226. ⚠️: In PyWebIO, you can't show multiple popup windows at the same time. Before displaying a new pop-up window,
  1227. the existing popup on the page will be automatically closed. You can use `close_popup()` to close the popup manually.
  1228. :param str title: The title of the popup.
  1229. :type content: list/str/put_xxx()
  1230. :param content: The content of the popup can be a string, the put_xxx() calls , or a list of them.
  1231. :param str size: The size of popup window. Available values are: ``'large'``, ``'normal'`` and ``'small'``.
  1232. :param bool implicit_close: If enabled, the popup can be closed implicitly by clicking the content outside
  1233. the popup window or pressing the ``Esc`` key. Default is ``False``.
  1234. :param bool closable: Whether the user can close the popup window. By default, the user can close the popup
  1235. by clicking the close button in the upper right of the popup window.
  1236. When set to ``False``, the popup window can only be closed by :func:`popup_close()`,
  1237. at this time the ``implicit_close`` parameter will be ignored.
  1238. ``popup()`` can be used in 3 ways: direct call, context manager, and decorator.
  1239. * direct call:
  1240. .. exportable-codeblock::
  1241. :name: popup
  1242. :summary: `popup()` usage
  1243. popup('popup title', 'popup text content', size=PopupSize.SMALL)
  1244. ## ----
  1245. popup('Popup title', [
  1246. put_html('<h3>Popup Content</h3>'),
  1247. 'html: <br/>',
  1248. put_table([['A', 'B'], ['C', 'D']]),
  1249. put_buttons(['close_popup()'], onclick=lambda _: close_popup())
  1250. ])
  1251. * context manager:
  1252. .. exportable-codeblock::
  1253. :name: popup-context
  1254. :summary: `popup()` as context manager
  1255. with popup('Popup title') as s:
  1256. put_html('<h3>Popup Content</h3>')
  1257. put_text('html: <br/>')
  1258. put_buttons([('clear()', s)], onclick=clear)
  1259. put_text('Also work!', scope=s)
  1260. The context manager will open a new output scope and return the scope name.
  1261. The output in the context manager will be displayed on the popup window by default.
  1262. After the context manager exits, the popup window will not be closed.
  1263. You can still use the ``scope`` parameter of the output function to output to the popup.
  1264. * decorator:
  1265. .. exportable-codeblock::
  1266. :name: popup-decorator
  1267. :summary: `popup()` as decorator
  1268. @popup('Popup title')
  1269. def show_popup():
  1270. put_html('<h3>Popup Content</h3>')
  1271. put_text("I'm in a popup!")
  1272. ...
  1273. show_popup()
  1274. """
  1275. if content is None:
  1276. content = []
  1277. if not isinstance(content, (list, tuple, OutputList)):
  1278. content = [content]
  1279. for item in content:
  1280. assert isinstance(item, (str, Output)), "popup() content must be list of str/put_xxx()"
  1281. dom_id = random_str(10)
  1282. send_msg(cmd='popup', spec=dict(content=Output.dump_dict(content), title=title, size=size,
  1283. implicit_close=implicit_close, closable=closable,
  1284. dom_id=scope2dom(dom_id, no_css_selector=True)))
  1285. return use_scope_(dom_id)
  1286. def close_popup():
  1287. """Close the current popup window.
  1288. See also: `popup()`
  1289. """
  1290. send_msg(cmd='close_popup')
  1291. def toast(content, duration=2, position='center', color='info', onclick=None):
  1292. """Show a notification message.
  1293. :param str content: Notification content.
  1294. :param float duration: The duration of the notification display, in seconds. `0` means not to close automatically
  1295. (at this time, a close button will be displayed next to the message, and the user can close the message manually)
  1296. :param str position: Where to display the notification message. Available values are `'left'`, `'center'` and `'right'`.
  1297. :param str color: Background color of the notification.
  1298. Available values are `'info'`, `'error'`, `'warn'`, `'success'` or hexadecimal color value starting with `'#'`
  1299. :param callable onclick: The callback function when the notification message is clicked.
  1300. The callback function receives no parameters.
  1301. Note: When in :ref:`Coroutine-based session <coroutine_based_session>`, the callback can be a coroutine function.
  1302. Example:
  1303. .. exportable-codeblock::
  1304. :name: toast
  1305. :summary: `toast()` usage
  1306. def show_msg():
  1307. put_text("You clicked the notification.")
  1308. toast('New messages', position='right', color='#2188ff', duration=0, onclick=show_msg)
  1309. """
  1310. colors = {
  1311. 'info': '#1565c0',
  1312. 'error': '#e53935',
  1313. 'warn': '#ef6c00',
  1314. 'success': '#2e7d32'
  1315. }
  1316. color = colors.get(color, color)
  1317. callback_id = output_register_callback(lambda _: onclick()) if onclick is not None else None
  1318. send_msg(cmd='toast', spec=dict(content=content, duration=int(duration * 1000), position=position,
  1319. color=color, callback_id=callback_id))
  1320. clear_scope = clear
  1321. def use_scope(name=None, clear=False, **kwargs):
  1322. """use_scope(name=None, clear=False)
  1323. Open or enter a scope. Can be used as context manager and decorator.
  1324. See :ref:`User manual - use_scope() <use_scope>`
  1325. :param str name: Scope name. If it is None, a globally unique scope name is generated.
  1326. (When used as context manager, the context manager will return the scope name)
  1327. :param bool clear: Whether to clear the contents of the scope before entering the scope.
  1328. :Usage:
  1329. ::
  1330. with use_scope(...) as scope_name:
  1331. put_xxx()
  1332. @use_scope(...)
  1333. def app():
  1334. put_xxx()
  1335. """
  1336. # For backward compatible
  1337. # :param bool create_scope: Whether to create scope when scope does not exist.
  1338. # :param scope_params: Extra parameters passed to `set_scope()` when need to create scope.
  1339. # Only available when ``create_scope=True``.
  1340. create_scope = kwargs.pop('create_scope', True)
  1341. scope_params = kwargs
  1342. if name is None:
  1343. name = random_str(10)
  1344. else:
  1345. assert is_html_safe_value(name), "Scope name only allow letter/digit/'_'/'-' char."
  1346. def before_enter():
  1347. if create_scope:
  1348. if_exist = 'clear' if clear else None
  1349. set_scope(name, if_exist=if_exist, **scope_params)
  1350. return use_scope_(name=name, before_enter=before_enter)
  1351. class use_scope_:
  1352. def __init__(self, name, before_enter=None):
  1353. self.before_enter = before_enter
  1354. self.name = name
  1355. def __enter__(self):
  1356. if self.before_enter:
  1357. self.before_enter()
  1358. get_current_session().push_scope(self.name)
  1359. return self.name
  1360. def __exit__(self, exc_type, exc_val, exc_tb):
  1361. """
  1362. If this method returns True, it means that the context manager can handle the exception,
  1363. so that the with statement terminates the propagation of the exception
  1364. """
  1365. get_current_session().pop_scope()
  1366. return False # Propagate Exception
  1367. def __call__(self, func):
  1368. """decorator implement"""
  1369. @wraps(func)
  1370. def wrapper(*args, **kwargs):
  1371. self.__enter__()
  1372. try:
  1373. return func(*args, **kwargs)
  1374. finally:
  1375. self.__exit__(None, None, None)
  1376. @wraps(func)
  1377. async def coro_wrapper(*args, **kwargs):
  1378. self.__enter__()
  1379. try:
  1380. return await func(*args, **kwargs)
  1381. finally:
  1382. self.__exit__(None, None, None)
  1383. if iscoroutinefunction(func):
  1384. return coro_wrapper
  1385. else:
  1386. return wrapper