output.py 73 KB

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