output.py 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768
  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()`
  524. :param buttons:
  525. {label:, value:, }
  526. (label, value, )
  527. single value, label=value
  528. :return: [{value:, label:, }, ...]
  529. """
  530. btns = []
  531. for btn in buttons:
  532. btn = copy.deepcopy(btn)
  533. if isinstance(btn, Mapping):
  534. assert 'value' in btn and 'label' in btn, 'actions item must have value and label key'
  535. elif isinstance(btn, (list, tuple)):
  536. assert len(btn) == 2, 'actions item format error'
  537. btn = dict(zip(('label', 'value'), btn))
  538. else:
  539. btn = dict(value=btn, label=btn)
  540. btns.append(btn)
  541. return btns
  542. def put_buttons(buttons, onclick, small=None, link_style=False, outline=False, group=False, scope=None,
  543. position=OutputPosition.BOTTOM, **callback_options) -> Output:
  544. """
  545. Output a group of buttons and bind click event
  546. :param list buttons: Button list. The available formats of list items are:
  547. * dict: ``{label:(str)button label, value:(str)button value, color:(str, optional)button color}``
  548. * tuple or list: ``(label, value)``
  549. * single value: label and value of option use the same value
  550. The ``value`` of button can be any JSON serializable object.
  551. The ``color`` of button can be one of: `primary`, `secondary`, `success`, `danger`, `warning`, `info`, `light`, `dark`.
  552. Example:
  553. .. exportable-codeblock::
  554. :name: put_buttons-btn_class
  555. :summary: `put_buttons()`
  556. put_buttons([dict(label='success', value='s', color='success')], onclick=...) # ..doc-only
  557. put_buttons([ # ..demo-only
  558. dict(label=i, value=i, color=i) # ..demo-only
  559. for i in ['primary', 'secondary', 'success', 'danger', 'warning', 'info', 'light', 'dark'] # ..demo-only
  560. ], onclick=put_text) # ..demo-only
  561. :type onclick: callable / list
  562. :param onclick: Callback which will be called when button is clicked. ``onclick`` can be a callable object or a list of it.
  563. If ``onclick`` is callable object, its signature is ``onclick(btn_value)``. ``btn_value`` is ``value`` of the button that is clicked.
  564. 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.
  565. Tip: You can use ``functools.partial`` to save more context information in ``onclick``.
  566. Note: When in :ref:`Coroutine-based session <coroutine_based_session>`, the callback can be a coroutine function.
  567. :param bool small: Whether to use small size button. Default is False.
  568. :param bool link_style: Whether to use link style button. Default is False
  569. :param bool outline: Whether to use outline style button. Default is False
  570. :param bool group: Whether to group the buttons together. Default is False
  571. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  572. :param callback_options: Other options of the ``onclick`` callback. There are different options according to the session implementation
  573. When in Coroutine-based Session:
  574. * mutex_mode: Default is ``False``. If set to ``True``, new click event will be ignored when the current callback is running.
  575. This option is available only when ``onclick`` is a coroutine function.
  576. When in Thread-based Session:
  577. * serial_mode: Default is ``False``, and every time a callback is triggered,
  578. the callback function will be executed immediately in a new thread.
  579. If set ``serial_mode`` to ``True``
  580. After enabling serial_mode, the button's callback will be executed serially in a resident thread in the session,
  581. and all other new click event callbacks (including the ``serial_mode=False`` callback) will be queued for
  582. the current click event to complete. If the callback function runs for a short time,
  583. you can turn on ``serial_mode`` to improve performance.
  584. Example:
  585. .. exportable-codeblock::
  586. :name: put_buttons
  587. :summary: `put_buttons()` usage
  588. from functools import partial
  589. def row_action(choice, id):
  590. put_text("You click %s button with id: %s" % (choice, id))
  591. put_buttons(['edit', 'delete'], onclick=partial(row_action, id=1))
  592. ## ----
  593. def edit():
  594. put_text("You click edit button")
  595. def delete():
  596. put_text("You click delete button")
  597. put_buttons(['edit', 'delete'], onclick=[edit, delete])
  598. """
  599. btns = _format_button(buttons)
  600. if isinstance(onclick, Sequence):
  601. assert len(btns) == len(onclick), "`onclick` and `buttons` must be same length."
  602. for idx, btn in enumerate(btns):
  603. btn['value'] = idx
  604. def click_callback(btn_val):
  605. if isinstance(onclick, Sequence):
  606. return onclick[btn_val]()
  607. else:
  608. return onclick(btn_val)
  609. callback_id = output_register_callback(click_callback, **callback_options)
  610. spec = _get_output_spec('buttons', callback_id=callback_id, buttons=btns, small=small,
  611. scope=scope, position=position, link=link_style, outline=outline, group=group)
  612. return Output(spec)
  613. def put_button(label, onclick, color=None, small=None, link_style=False, outline=False, scope=None,
  614. position=OutputPosition.BOTTOM) -> Output:
  615. """Output a single button and bind click event to it.
  616. :param str label: Button label
  617. :param callable onclick: Callback which will be called when button is clicked.
  618. :param str color: The color of the button,
  619. can be one of: `primary`, `secondary`, `success`, `danger`, `warning`, `info`, `light`, `dark`.
  620. :param - small, link_style, outline, scope, position: Those arguments have the same meaning as for `put_buttons()`
  621. Example:
  622. .. exportable-codeblock::
  623. :name: put_button
  624. :summary: `put_button()` usage
  625. put_button("click me", onclick=lambda: toast("Clicked"), color='success', outline=True)
  626. .. versionadded:: 1.4
  627. """
  628. return put_buttons([{'label': label, 'value': '', 'color': color or 'primary'}], onclick=[onclick],
  629. small=small, link_style=link_style, outline=outline, scope=scope, position=position)
  630. def put_image(src, format=None, title='', width=None, height=None,
  631. scope=None, position=OutputPosition.BOTTOM) -> Output:
  632. """Output image
  633. :param src: Source of image. It can be a string specifying image URL, a bytes-like object specifying
  634. the binary content of an image or an instance of ``PIL.Image.Image``
  635. :param str title: Image description.
  636. :param str width: The width of image. It can be CSS pixels (like `'30px'`) or percentage (like `'10%'`).
  637. :param str height: The height of image. It can be CSS pixels (like `'30px'`) or percentage (like `'10%'`).
  638. If only one value of ``width`` and ``height`` is specified, the browser will scale image according to its original size.
  639. :param str format: Image format, optinoal. e.g.: ``png``, ``jpeg``, ``gif``, etc. Only available when `src` is non-URL
  640. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  641. Example:
  642. .. exportable-codeblock::
  643. :name: put_image
  644. :summary: `put_image()` usage
  645. from pywebio import STATIC_PATH # ..demo-only
  646. img = open(STATIC_PATH + '/image/favicon_open_32.png', 'rb').read() # ..demo-only
  647. img = open('/path/to/some/image.png', 'rb').read() # ..doc-only
  648. put_image(img, width='50px')
  649. ## ----
  650. put_image('https://www.python.org/static/img/python-logo.png')
  651. """
  652. if isinstance(src, PILImage):
  653. format = format or src.format or 'JPEG'
  654. imgByteArr = io.BytesIO()
  655. src.save(imgByteArr, format=format)
  656. src = imgByteArr.getvalue()
  657. if isinstance(src, (bytes, bytearray)):
  658. b64content = b64encode(src).decode('ascii')
  659. format = '' if format is None else ('image/%s' % format)
  660. format = html.escape(format, quote=True)
  661. src = "data:{format};base64, {b64content}".format(format=format, b64content=b64content)
  662. width = 'width="%s"' % html.escape(width, quote=True) if width is not None else ''
  663. height = 'height="%s"' % html.escape(height, quote=True) if height is not None else ''
  664. tag = r'<img src="{src}" alt="{title}" {width} {height}/>'.format(src=src, title=html.escape(title, quote=True),
  665. height=height, width=width)
  666. return put_html(tag, scope=scope, position=position)
  667. def put_file(name, content, label=None, scope=None, position=OutputPosition.BOTTOM) -> Output:
  668. """Output a link to download a file
  669. To show a link with the file name on the browser. When click the link, the browser automatically downloads the file.
  670. :param str name: File name downloaded as
  671. :param content: File content. It is a bytes-like object
  672. :param str label: The label of the download link, which is the same as the file name by default.
  673. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  674. Example:
  675. .. exportable-codeblock::
  676. :name: put_file
  677. :summary: `put_file()` usage
  678. content = open('./some-file', 'rb').read() # ..doc-only
  679. content = open('README.md', 'rb').read() # ..demo-only
  680. put_file('hello-world.txt', content, 'download me')
  681. """
  682. if label is None:
  683. label = name
  684. output = put_buttons(buttons=[label], link_style=True,
  685. onclick=[lambda: download(name, content)],
  686. scope=scope, position=position)
  687. return output
  688. def put_link(name, url=None, app=None, new_window=False, scope=None,
  689. position=OutputPosition.BOTTOM) -> Output:
  690. """Output hyperlinks to other web page or PyWebIO Application page.
  691. :param str name: The label of the link
  692. :param str url: Target url
  693. :param str app: Target PyWebIO Application name. See also: :ref:`Server mode <server_and_script_mode>`
  694. :param bool new_window: Whether to open the link in a new window
  695. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  696. The ``url`` and ``app`` parameters must specify one but not both
  697. """
  698. assert bool(url is None) != bool(app is None), "Must set `url` or `app` parameter but not both"
  699. href = 'javascript:WebIO.openApp(%r, %d)' % (app, new_window) if app is not None else url
  700. target = '_blank' if (new_window and url) else '_self'
  701. tag = '<a href="{href}" target="{target}">{name}</a>'.format(
  702. href=html.escape(href, quote=True), target=target, name=html.escape(name))
  703. return put_html(tag, scope=scope, position=position)
  704. def put_processbar(name, init=0, label=None, auto_close=False, scope=None,
  705. position=OutputPosition.BOTTOM) -> Output:
  706. """Output a process bar
  707. :param str name: The name of the progress bar, which is the unique identifier of the progress bar
  708. :param float init: The initial progress value of the progress bar. The value is between 0 and 1
  709. :param str label: The label of process bar. The default is the percentage value of the current progress.
  710. :param bool auto_close: Whether to remove the progress bar after the progress is completed
  711. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  712. Example:
  713. .. exportable-codeblock::
  714. :name: put_processbar
  715. :summary: `put_processbar()` usage
  716. import time
  717. put_processbar('bar');
  718. for i in range(1, 11):
  719. set_processbar('bar', i / 10)
  720. time.sleep(0.1)
  721. """
  722. processbar_id = 'webio-processbar-%s' % name
  723. percentage = init * 100
  724. label = '%.1f%%' % percentage if label is None else label
  725. tpl = """<div class="progress" style="margin-top: 4px;">
  726. <div id="{{elem_id}}" class="progress-bar bg-info progress-bar-striped progress-bar-animated" role="progressbar"
  727. style="width: {{percentage}}%;" aria-valuenow="{{init}}" aria-valuemin="0" aria-valuemax="1" data-auto-close="{{auto_close}}">{{label}}
  728. </div>
  729. </div>"""
  730. return put_widget(tpl, data=dict(elem_id=processbar_id, init=init, label=label,
  731. percentage=percentage, auto_close=int(bool(auto_close))), scope=scope,
  732. position=position)
  733. def set_processbar(name, value, label=None):
  734. """Set the progress of progress bar
  735. :param str name: The name of the progress bar
  736. :param float value: The progress value of the progress bar. The value is between 0 and 1
  737. :param str label: The label of process bar. The default is the percentage value of the current progress.
  738. See also: `put_processbar()`
  739. """
  740. from pywebio.session import run_js
  741. processbar_id = 'webio-processbar-%s' % name
  742. percentage = value * 100
  743. label = '%.1f%%' % percentage if label is None else label
  744. js_code = """
  745. let bar = $("#{processbar_id}");
  746. bar[0].style.width = "{percentage}%";
  747. bar.attr("aria-valuenow", "{value}");
  748. bar.text({label!r});
  749. """.format(processbar_id=processbar_id, percentage=percentage, value=value, label=label)
  750. if value == 1:
  751. js_code += "if(bar.data('autoClose')=='1')bar.parent().remove();"
  752. run_js(js_code)
  753. def put_loading(shape='border', color='dark', scope=None, position=OutputPosition.BOTTOM) -> Output:
  754. """Output loading prompt
  755. :param str shape: The shape of loading prompt. The available values are: `'border'` (default)、 `'grow'`
  756. :param str color: The color of loading prompt. The available values are: `'primary'` 、 `'secondary'` 、
  757. `'success'` 、 `'danger'` 、 `'warning'` 、`'info'` 、`'light'` 、 `'dark'` (default)
  758. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  759. `put_loading()` can be used in 2 ways: direct call and context manager:
  760. .. exportable-codeblock::
  761. :name: put_loading
  762. :summary: `put_loading()` usage
  763. for shape in ('border', 'grow'):
  764. for color in ('primary', 'secondary', 'success', 'danger', 'warning', 'info', 'light', 'dark'):
  765. put_text(shape, color)
  766. put_loading(shape=shape, color=color)
  767. ## ----
  768. import time # ..demo-only
  769. # Use as context manager, the loading prompt will disappear automatically when the context block exits.
  770. with put_loading():
  771. time.sleep(3) # Some time-consuming operations
  772. put_text("The answer of the universe is 42")
  773. ## ----
  774. # using style() to set the size of the loading prompt
  775. put_loading().style('width:4rem; height:4rem')
  776. """
  777. assert shape in ('border', 'grow'), "shape must in ('border', 'grow')"
  778. assert color in {'primary', 'secondary', 'success', 'danger', 'warning', 'info', 'light', 'dark'}
  779. html = """<div class="spinner-{shape} text-{color}" role="status">
  780. <span class="sr-only">Loading...</span>
  781. </div>""".format(shape=shape, color=color)
  782. scope_name = random_str(10)
  783. def enter(self):
  784. self.spec['container_dom_id'] = scope2dom(scope_name, no_css_selector=True)
  785. self.send()
  786. return scope_name
  787. def exit_(self, exc_type, exc_val, exc_tb):
  788. remove(scope_name)
  789. return False # Propagate Exception
  790. return put_html(html, sanitize=False, scope=scope, position=position). \
  791. enable_context_manager(custom_enter=enter, custom_exit=exit_)
  792. @safely_destruct_output_when_exp('content')
  793. def put_collapse(title, content=[], open=False, scope=None, position=OutputPosition.BOTTOM) -> Output:
  794. """Output collapsible content
  795. :param str title: Title of content
  796. :type content: list/str/put_xxx()
  797. :param content: The content can be a string, the ``put_xxx()`` calls , or a list of them.
  798. :param bool open: Whether to expand the content. Default is ``False``.
  799. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  800. Example:
  801. .. exportable-codeblock::
  802. :name: put_collapse
  803. :summary: `put_collapse()` usage
  804. put_collapse('Collapse title', [
  805. 'text',
  806. put_markdown('~~Strikethrough~~'),
  807. put_table([
  808. ['Commodity', 'Price'],
  809. ['Apple', '5.5'],
  810. ])
  811. ], open=True)
  812. ## ----
  813. put_collapse('Large text', 'Awesome PyWebIO! '*30)
  814. """
  815. if not isinstance(content, (list, tuple, OutputList)):
  816. content = [content]
  817. for item in content:
  818. assert isinstance(item, (str, Output)), "put_collapse() content must be list of str/put_xxx()"
  819. tpl = """<details {{#open}}open{{/open}}>
  820. <summary>{{title}}</summary>
  821. {{#contents}}
  822. {{& pywebio_output_parse}}
  823. {{/contents}}
  824. </details>"""
  825. return put_widget(tpl, dict(title=title, contents=content, open=open), scope=scope,
  826. position=position).enable_context_manager()
  827. @safely_destruct_output_when_exp('content')
  828. def put_scrollable(content=[], height=400, keep_bottom=False, horizon_scroll=False, border=True,
  829. scope=None, position=OutputPosition.BOTTOM, **kwargs) -> Output:
  830. """Output a fixed height content area. scroll bar is displayed when the content exceeds the limit
  831. :type content: list/str/put_xxx()
  832. :param content: The content can be a string, the ``put_xxx()`` calls , or a list of them.
  833. :param int/tuple height: The height of the area (in pixels).
  834. ``height`` parameter also accepts ``(min_height, max_height)`` to indicate the range of height, for example,
  835. ``(100, 200)`` means that the area has a minimum height of 100 pixels and a maximum of 200 pixels.
  836. :param bool keep_bottom: Whether to keep the content area scrolled to the bottom when updated.
  837. :param bool horizon_scroll: Whether to use the horizontal scroll bar
  838. :param bool border: Whether to show border
  839. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  840. Example:
  841. .. exportable-codeblock::
  842. :name: put_scrollable
  843. :summary: `put_scrollable()` usage
  844. import time
  845. o = output("You can click the area to prevent auto scroll.")
  846. put_scrollable(o, height=200, keep_bottom=True)
  847. while 1:
  848. o.append(time.time())
  849. time.sleep(0.5)
  850. .. versionchanged:: 1.1
  851. add ``height`` parameter,remove ``max_height`` parameter;
  852. add ``keep_bottom`` parameter
  853. """
  854. if not isinstance(content, (list, tuple, OutputList)):
  855. content = [content]
  856. content = [i if isinstance(i, Output) else put_text(i) for i in content]
  857. if 'max_height' in kwargs:
  858. import warnings
  859. warnings.warn("`max_height` parameter is deprecated in `put_scrollable()`, use `height` instead.",
  860. DeprecationWarning, stacklevel=3)
  861. height = kwargs['max_height'] # Backward compatible
  862. try:
  863. min_height, max_height = height
  864. except Exception:
  865. min_height, max_height = height, height
  866. spec = _get_output_spec('scrollable', contents=content, min_height=min_height, max_height=max_height,
  867. keep_bottom=keep_bottom, horizon_scroll=horizon_scroll, border=border, scope=scope,
  868. position=position)
  869. return Output(spec)
  870. @safely_destruct_output_when_exp('tabs')
  871. def put_tabs(tabs, scope=None, position=OutputPosition.BOTTOM) -> Output:
  872. """Output tabs.
  873. :param list tabs: Tab list, each item is a dict: ``{"title": "Title", "content": ...}`` .
  874. The ``content`` can be a string, the ``put_xxx()`` calls , or a list of them.
  875. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  876. .. exportable-codeblock::
  877. :name: put_tabs
  878. :summary: `put_tabs()` usage
  879. put_tabs([
  880. {'title': 'Text', 'content': 'Hello world'},
  881. {'title': 'Markdown', 'content': put_markdown('~~Strikethrough~~')},
  882. {'title': 'More content', 'content': [
  883. put_table([
  884. ['Commodity', 'Price'],
  885. ['Apple', '5.5'],
  886. ['Banana', '7'],
  887. ]),
  888. put_link('pywebio', 'https://github.com/wang0618/PyWebIO')
  889. ]},
  890. ])
  891. .. versionadded:: 1.3
  892. """
  893. for tab in tabs:
  894. assert 'title' in tab and 'content' in tab
  895. spec = _get_output_spec('tabs', tabs=tabs, scope=scope, position=position)
  896. return Output(spec)
  897. @safely_destruct_output_when_exp('data')
  898. def put_widget(template, data, scope=None, position=OutputPosition.BOTTOM) -> Output:
  899. """Output your own widget
  900. :param template: html template, using `mustache.js <https://github.com/janl/mustache.js>`_ syntax
  901. :param dict data: Data used to render the template.
  902. The data can include the ``put_xxx()`` calls, and the JS function ``pywebio_output_parse`` can be used to
  903. parse the content of ``put_xxx()``. For string input, ``pywebio_output_parse`` will parse into text.
  904. ⚠️:When using the ``pywebio_output_parse`` function, you need to turn off the html escaping of mustache:
  905. ``{{& pywebio_output_parse}}``, see the example below.
  906. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  907. :Example:
  908. .. exportable-codeblock::
  909. :name: put_widget
  910. :summary: Use `put_widget()` to output your own widget
  911. tpl = '''
  912. <details {{#open}}open{{/open}}>
  913. <summary>{{title}}</summary>
  914. {{#contents}}
  915. {{& pywebio_output_parse}}
  916. {{/contents}}
  917. </details>
  918. '''
  919. put_widget(tpl, {
  920. "open": True,
  921. "title": 'More content',
  922. "contents": [
  923. 'text',
  924. put_markdown('~~Strikethrough~~'),
  925. put_table([
  926. ['Commodity', 'Price'],
  927. ['Apple', '5.5'],
  928. ['Banana', '7'],
  929. ])
  930. ]
  931. })
  932. """
  933. spec = _get_output_spec('custom_widget', template=template, data=data, scope=scope, position=position)
  934. return Output(spec)
  935. @safely_destruct_output_when_exp('content')
  936. def put_row(content=[], size=None, scope=None, position=OutputPosition.BOTTOM) -> Output:
  937. """Use row layout to output content. The content is arranged horizontally
  938. :param list content: Content list, the item is ``put_xxx()`` call or ``None``. ``None`` represents the space between the output
  939. :param str size:
  940. | Used to indicate the width of the items, is a list of width values separated by space.
  941. | Each width value corresponds to the items one-to-one. (``None`` item should also correspond to a width value).
  942. | By default, ``size`` assigns a width of 10 pixels to the ``None`` item, and distributes the width equally to the remaining items.
  943. Available format of width value are:
  944. - pixels: like ``100px``
  945. - percentage: Indicates the percentage of available width. like ``33.33%``
  946. - ``fr`` keyword: Represents a scale relationship, 2fr represents twice the width of 1fr
  947. - ``auto`` keyword: Indicates that the length is determined by the browser
  948. - ``minmax(min, max)`` : Generate a length range, indicating that the length is within this range.
  949. It accepts two parameters, minimum and maximum.
  950. For example: ``minmax(100px, 1fr)`` means the length is not less than 100px and not more than 1fr
  951. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  952. :Example:
  953. .. exportable-codeblock::
  954. :name: put_row
  955. :summary: `put_row()` usage
  956. # Two code blocks of equal width, separated by 10 pixels
  957. put_row([put_code('A'), None, put_code('B')])
  958. ## ----
  959. # The width ratio of the left and right code blocks is 2:3, which is equivalent to size='2fr 10px 3fr'
  960. put_row([put_code('A'), None, put_code('B')], size='40% 10px 60%')
  961. """
  962. return _row_column_layout(content, flow='column', size=size, scope=scope,
  963. position=position).enable_context_manager()
  964. @safely_destruct_output_when_exp('content')
  965. def put_column(content=[], size=None, scope=None, position=OutputPosition.BOTTOM) -> Output:
  966. """Use column layout to output content. The content is arranged vertically
  967. :param list content: Content list, the item is ``put_xxx()`` call or ``None``. ``None`` represents the space between the output
  968. :param str size: Used to indicate the width of the items, is a list of width values separated by space.
  969. The format is the same as the ``size`` parameter of the `put_row()` function.
  970. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  971. """
  972. return _row_column_layout(content, flow='row', size=size, scope=scope, position=position).enable_context_manager()
  973. def _row_column_layout(content, flow, size, scope=None, position=OutputPosition.BOTTOM) -> Output:
  974. if not isinstance(content, (list, tuple, OutputList)):
  975. content = [content]
  976. if not size:
  977. size = ' '.join('1fr' if c is not None else '10px' for c in content)
  978. content = [c if c is not None else put_html('<div></div>') for c in content]
  979. for item in content:
  980. assert isinstance(item, Output), "put_row()/put_column()'s content must be list of put_xxx()"
  981. style = 'grid-auto-flow: {flow}; grid-template-{flow}s: {size};'.format(flow=flow, size=size)
  982. tpl = """
  983. <div style="display: grid; %s">
  984. {{#contents}}
  985. {{& pywebio_output_parse}}
  986. {{/contents}}
  987. </div>""".strip() % html.escape(style, quote=True)
  988. return put_widget(template=tpl, data=dict(contents=content), scope=scope,
  989. position=position)
  990. @safely_destruct_output_when_exp('content')
  991. def put_grid(content, cell_width='auto', cell_height='auto', cell_widths=None, cell_heights=None, direction='row',
  992. scope=None, position=OutputPosition.BOTTOM) -> Output:
  993. """Output content using grid layout
  994. :param content: Content of grid, which is a two-dimensional list. The item of list is ``put_xxx()`` call or ``None``.
  995. ``None`` represents the space between the output. The item can use the `span()` to set the cell span.
  996. :param str cell_width: The width of grid cell.
  997. :param str cell_height: The height of grid cell.
  998. :param str cell_widths: The width of each column of the grid. The width values are separated by a space.
  999. Can not use ``cell_widths`` and ``cell_width`` at the same time
  1000. :param str cell_heights: The height of each row of the grid. The height values are separated by a space.
  1001. Can not use ``cell_heights`` and ``cell_height`` at the same time
  1002. :param str direction: Controls how auto-placed items get inserted in the grid.
  1003. Can be ``'row'``(default) or ``'column'`` .
  1004. | ``'row'`` : Places items by filling each row
  1005. | ``'column'`` : Places items by filling each column
  1006. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  1007. The format of width/height value in ``cell_width``,``cell_height``,``cell_widths``,``cell_heights``
  1008. can refer to the ``size`` parameter of the `put_row()` function.
  1009. :Example:
  1010. .. exportable-codeblock::
  1011. :name: put_grid
  1012. :summary: `put_grid()` usage
  1013. put_grid([
  1014. [put_text('A'), put_text('B'), put_text('C')],
  1015. [None, span(put_text('D'), col=2, row=1)],
  1016. [put_text('E'), put_text('F'), put_text('G')],
  1017. ], cell_width='100px', cell_height='100px')
  1018. """
  1019. assert direction in ('row', 'column'), '"direction" parameter must be "row" or "column"'
  1020. lens = [0] * len(content)
  1021. for x in range(len(content)):
  1022. for y in range(len(content[x])):
  1023. cell = content[x][y]
  1024. if isinstance(cell, span_):
  1025. for i in range(cell.row):
  1026. lens[x + i] += cell.col
  1027. css = 'grid-row-start: span {row}; grid-column-start: span {col};'.format(row=cell.row, col=cell.col)
  1028. elem = put_html('<div></div>') if cell.content is None else cell.content
  1029. content[x][y] = elem.style(css)
  1030. else:
  1031. lens[x] += 1
  1032. if content[x][y] is None:
  1033. content[x][y] = put_html('<div></div>')
  1034. # 为长度不足的行添加空元素
  1035. # Add empty elements for rows with insufficient length
  1036. m = max(lens)
  1037. for idx, i in enumerate(content):
  1038. i.extend(put_html('<div></div>') for _ in range(m - lens[idx]))
  1039. row_cnt, col_cnt = len(content), m
  1040. if direction == 'column':
  1041. row_cnt, col_cnt = m, len(content)
  1042. if not cell_widths:
  1043. cell_widths = 'repeat({col_cnt},{cell_width})'.format(col_cnt=col_cnt, cell_width=cell_width)
  1044. if not cell_heights:
  1045. cell_heights = 'repeat({row_cnt},{cell_height})'.format(row_cnt=row_cnt, cell_height=cell_height)
  1046. css = ('grid-auto-flow: {flow};'
  1047. 'grid-template-columns: {cell_widths};'
  1048. 'grid-template-rows: {cell_heights};'
  1049. ).format(flow=direction, cell_heights=cell_heights, cell_widths=cell_widths)
  1050. tpl = """
  1051. <div style="display: grid; %s">
  1052. {{#contents}}
  1053. {{#.}}
  1054. {{& pywebio_output_parse}}
  1055. {{/.}}
  1056. {{/contents}}
  1057. </div>""".strip() % html.escape(css, quote=True)
  1058. return put_widget(template=tpl, data=dict(contents=content), scope=scope, position=position)
  1059. @safely_destruct_output_when_exp('content')
  1060. def put_scope(name, content=[], scope=None, position=OutputPosition.BOTTOM) -> Output:
  1061. """Output a scope
  1062. :param str name:
  1063. :param list/put_xxx() content: The initial content of the scope, can be ``put_xxx()`` or a list of it.
  1064. :param int scope, position: Those arguments have the same meaning as for `put_text()`
  1065. """
  1066. if not isinstance(content, list):
  1067. content = [content]
  1068. assert is_html_safe_value(name), "Scope name only allow letter/digit/'_'/'-' char."
  1069. dom_id = scope2dom(name, no_css_selector=True)
  1070. spec = _get_output_spec('scope', dom_id=dom_id, contents=content, scope=scope, position=position)
  1071. return Output(spec)
  1072. @safely_destruct_output_when_exp('contents')
  1073. def output(*contents):
  1074. """Placeholder of output
  1075. .. deprecated:: 1.5
  1076. See :ref:`User Guide <put_scope>` for new way to set css style for output.
  1077. ``output()`` can be passed in anywhere that ``put_xxx()`` can passed in. A handler it returned by ``output()``,
  1078. and after being output, the content can also be modified by the handler (See code example below).
  1079. :param contents: The initial contents to be output.
  1080. The item is ``put_xxx()`` call, and any other type will be converted to ``put_text(content)``.
  1081. :return: An OutputHandler instance, the methods of the instance are as follows:
  1082. * ``reset(*contents)`` : Reset original contents to ``contents``
  1083. * ``append(*contents)`` : Append ``contents`` to original contents
  1084. * ``insert(idx, *contents)`` : insert ``contents`` into original contents.
  1085. | when idx>=0, the output content is inserted before the element of the ``idx`` index.
  1086. | when idx<0, the output content is inserted after the element of the ``idx`` index.
  1087. Among them, the parameter ``contents`` is the same as ``output()``.
  1088. :Example:
  1089. .. exportable-codeblock::
  1090. :name: output
  1091. :summary: `output()` usage
  1092. hobby = output(put_text('Coding')) # equal to output('Coding')
  1093. put_table([
  1094. ['Name', 'Hobbies'],
  1095. ['Wang', hobby] # hobby is initialized to Coding
  1096. ])
  1097. ## ----
  1098. hobby.reset('Movie') # hobby is reset to Movie
  1099. ## ----
  1100. hobby.append('Music', put_text('Drama')) # append Music, Drama to hobby
  1101. ## ----
  1102. hobby.insert(0, put_markdown('**Coding**')) # insert the Coding into the top of the hobby
  1103. """
  1104. import warnings
  1105. warnings.warn("`pywebio.output.output()` is deprecated since v1.5 and will remove in the future version, "
  1106. "use `pywebio.output.put_scope()` instead", DeprecationWarning, stacklevel=2)
  1107. class OutputHandler(Output):
  1108. """
  1109. 与 `Output` 的不同在于, 不会在销毁时(__del__)自动输出
  1110. The difference with `Output` is that `OutputHandler` will not automatically output when destroyed (__del__)
  1111. """
  1112. def __del__(self):
  1113. pass
  1114. def __init__(self, spec, scope):
  1115. super().__init__(spec)
  1116. self.scope = scope
  1117. @safely_destruct_output_when_exp('outputs')
  1118. def reset(self, *outputs):
  1119. clear_scope(scope=self.scope)
  1120. self.append(*outputs)
  1121. @safely_destruct_output_when_exp('outputs')
  1122. def append(self, *outputs):
  1123. for o in outputs:
  1124. if not isinstance(o, Output):
  1125. o = put_text(o)
  1126. o.spec['scope'] = scope2dom(self.scope)
  1127. o.spec['position'] = OutputPosition.BOTTOM
  1128. o.send()
  1129. @safely_destruct_output_when_exp('outputs')
  1130. def insert(self, idx, *outputs):
  1131. """
  1132. idx可为负
  1133. idx can be negative
  1134. """
  1135. direction = 1 if idx >= 0 else -1
  1136. for acc, o in enumerate(outputs):
  1137. if not isinstance(o, Output):
  1138. o = put_text(o)
  1139. o.spec['scope'] = scope2dom(self.scope)
  1140. o.spec['position'] = idx + direction * acc
  1141. o.send()
  1142. contents = [c if isinstance(c, Output) else put_text(c) for c in contents]
  1143. dom_name = random_str(10)
  1144. tpl = """<div class="{{dom_class_name}}">
  1145. {{#contents}}
  1146. {{#.}}
  1147. {{& pywebio_output_parse}}
  1148. {{/.}}
  1149. {{/contents}}
  1150. </div>"""
  1151. out_spec = put_widget(template=tpl,
  1152. data=dict(contents=contents, dom_class_name=scope2dom(dom_name, no_css_selector=True)))
  1153. return OutputHandler(Output.dump_dict(out_spec), ('.', dom_name))
  1154. @safely_destruct_output_when_exp('outputs')
  1155. def style(outputs, css_style) -> Union[Output, OutputList]:
  1156. """Customize the css style of output content
  1157. .. deprecated:: 1.3
  1158. See :ref:`User Guide <style>` for new way to set css style for output.
  1159. :param outputs: The output content can be a ``put_xxx()`` call or a list of it.
  1160. :type outputs: list/put_xxx()
  1161. :param str css_style: css style string
  1162. :return: The output contents with css style added:
  1163. Note: If ``outputs`` is a list of ``put_xxx()`` calls, the style will be set for each item of the list.
  1164. And the return value can be used in anywhere accept a list of ``put_xxx()`` calls.
  1165. :Example:
  1166. .. exportable-codeblock::
  1167. :name: style-deprecated
  1168. :summary: `style()` usage
  1169. style(put_text('Red'), 'color:red')
  1170. ## ----
  1171. style([
  1172. put_text('Red'),
  1173. put_markdown('~~del~~')
  1174. ], 'color:red')
  1175. ## ----
  1176. put_table([
  1177. ['A', 'B'],
  1178. ['C', style(put_text('Red'), 'color:red')],
  1179. ])
  1180. ## ----
  1181. put_collapse('title', style([
  1182. put_text('text'),
  1183. put_markdown('~~del~~'),
  1184. ], 'margin-left:20px'))
  1185. """
  1186. import warnings
  1187. warnings.warn("`pywebio.output.style()` is deprecated since v1.3 and will remove in the future version, "
  1188. "use `put_xxx(...).style(...)` instead", DeprecationWarning, stacklevel=2)
  1189. if not isinstance(outputs, (list, tuple, OutputList)):
  1190. ol = [outputs]
  1191. else:
  1192. ol = outputs
  1193. outputs = OutputList(outputs)
  1194. for o in ol:
  1195. assert isinstance(o, Output), 'style() only accept put_xxx() input'
  1196. o.spec.setdefault('style', '')
  1197. o.spec['style'] += ';%s' % css_style
  1198. return outputs
  1199. @safely_destruct_output_when_exp('content')
  1200. def popup(title, content=None, size=PopupSize.NORMAL, implicit_close=True, closable=True):
  1201. """
  1202. Show a popup.
  1203. ⚠️: In PyWebIO, you can't show multiple popup windows at the same time. Before displaying a new pop-up window,
  1204. the existing popup on the page will be automatically closed. You can use `close_popup()` to close the popup manually.
  1205. :param str title: The title of the popup.
  1206. :type content: list/str/put_xxx()
  1207. :param content: The content of the popup can be a string, the put_xxx() calls , or a list of them.
  1208. :param str size: The size of popup window. Available values are: ``'large'``, ``'normal'`` and ``'small'``.
  1209. :param bool implicit_close: If enabled, the popup can be closed implicitly by clicking the content outside
  1210. the popup window or pressing the ``Esc`` key. Default is ``False``.
  1211. :param bool closable: Whether the user can close the popup window. By default, the user can close the popup
  1212. by clicking the close button in the upper right of the popup window.
  1213. When set to ``False``, the popup window can only be closed by :func:`popup_close()`,
  1214. at this time the ``implicit_close`` parameter will be ignored.
  1215. ``popup()`` can be used in 3 ways: direct call, context manager, and decorator.
  1216. * direct call:
  1217. .. exportable-codeblock::
  1218. :name: popup
  1219. :summary: `popup()` usage
  1220. popup('popup title', 'popup text content', size=PopupSize.SMALL)
  1221. ## ----
  1222. popup('Popup title', [
  1223. put_html('<h3>Popup Content</h3>'),
  1224. 'html: <br/>',
  1225. put_table([['A', 'B'], ['C', 'D']]),
  1226. put_buttons(['close_popup()'], onclick=lambda _: close_popup())
  1227. ])
  1228. * context manager:
  1229. .. exportable-codeblock::
  1230. :name: popup-context
  1231. :summary: `popup()` as context manager
  1232. with popup('Popup title') as s:
  1233. put_html('<h3>Popup Content</h3>')
  1234. put_text('html: <br/>')
  1235. put_buttons([('clear()', s)], onclick=clear)
  1236. put_text('Also work!', scope=s)
  1237. The context manager will open a new output scope and return the scope name.
  1238. The output in the context manager will be displayed on the popup window by default.
  1239. After the context manager exits, the popup window will not be closed.
  1240. You can still use the ``scope`` parameter of the output function to output to the popup.
  1241. * decorator:
  1242. .. exportable-codeblock::
  1243. :name: popup-decorator
  1244. :summary: `popup()` as decorator
  1245. @popup('Popup title')
  1246. def show_popup():
  1247. put_html('<h3>Popup Content</h3>')
  1248. put_text("I'm in a popup!")
  1249. ...
  1250. show_popup()
  1251. """
  1252. if content is None:
  1253. content = []
  1254. if not isinstance(content, (list, tuple, OutputList)):
  1255. content = [content]
  1256. for item in content:
  1257. assert isinstance(item, (str, Output)), "popup() content must be list of str/put_xxx()"
  1258. dom_id = random_str(10)
  1259. send_msg(cmd='popup', spec=dict(content=Output.dump_dict(content), title=title, size=size,
  1260. implicit_close=implicit_close, closable=closable,
  1261. dom_id=scope2dom(dom_id, no_css_selector=True)))
  1262. return use_scope_(dom_id)
  1263. def close_popup():
  1264. """Close the current popup window.
  1265. See also: `popup()`
  1266. """
  1267. send_msg(cmd='close_popup')
  1268. def toast(content, duration=2, position='center', color='info', onclick=None):
  1269. """Show a notification message.
  1270. :param str content: Notification content.
  1271. :param float duration: The duration of the notification display, in seconds. `0` means not to close automatically
  1272. (at this time, a close button will be displayed next to the message, and the user can close the message manually)
  1273. :param str position: Where to display the notification message. Available values are `'left'`, `'center'` and `'right'`.
  1274. :param str color: Background color of the notification.
  1275. Available values are `'info'`, `'error'`, `'warn'`, `'success'` or hexadecimal color value starting with `'#'`
  1276. :param callable onclick: The callback function when the notification message is clicked.
  1277. The callback function receives no parameters.
  1278. Note: When in :ref:`Coroutine-based session <coroutine_based_session>`, the callback can be a coroutine function.
  1279. Example:
  1280. .. exportable-codeblock::
  1281. :name: toast
  1282. :summary: `toast()` usage
  1283. def show_msg():
  1284. put_text("You clicked the notification.")
  1285. toast('New messages', position='right', color='#2188ff', duration=0, onclick=show_msg)
  1286. """
  1287. colors = {
  1288. 'info': '#1565c0',
  1289. 'error': '#e53935',
  1290. 'warn': '#ef6c00',
  1291. 'success': '#2e7d32'
  1292. }
  1293. color = colors.get(color, color)
  1294. callback_id = output_register_callback(lambda _: onclick()) if onclick is not None else None
  1295. send_msg(cmd='toast', spec=dict(content=content, duration=int(duration * 1000), position=position,
  1296. color=color, callback_id=callback_id))
  1297. clear_scope = clear
  1298. def use_scope(name=None, clear=False, **kwargs):
  1299. """use_scope(name=None, clear=False)
  1300. Open or enter a scope. Can be used as context manager and decorator.
  1301. See :ref:`User manual - use_scope() <use_scope>`
  1302. :param str name: Scope name. If it is None, a globally unique scope name is generated.
  1303. (When used as context manager, the context manager will return the scope name)
  1304. :param bool clear: Whether to clear the contents of the scope before entering the scope.
  1305. :Usage:
  1306. ::
  1307. with use_scope(...) as scope_name:
  1308. put_xxx()
  1309. @use_scope(...)
  1310. def app():
  1311. put_xxx()
  1312. """
  1313. # For backward compatible
  1314. # :param bool create_scope: Whether to create scope when scope does not exist.
  1315. # :param scope_params: Extra parameters passed to `set_scope()` when need to create scope.
  1316. # Only available when ``create_scope=True``.
  1317. create_scope = kwargs.pop('create_scope', True)
  1318. scope_params = kwargs
  1319. if name is None:
  1320. name = random_str(10)
  1321. else:
  1322. assert is_html_safe_value(name), "Scope name only allow letter/digit/'_'/'-' char."
  1323. def before_enter():
  1324. if create_scope:
  1325. if_exist = 'clear' if clear else None
  1326. set_scope(name, if_exist=if_exist, **scope_params)
  1327. return use_scope_(name=name, before_enter=before_enter)
  1328. class use_scope_:
  1329. def __init__(self, name, before_enter=None):
  1330. self.before_enter = before_enter
  1331. self.name = name
  1332. def __enter__(self):
  1333. if self.before_enter:
  1334. self.before_enter()
  1335. get_current_session().push_scope(self.name)
  1336. return self.name
  1337. def __exit__(self, exc_type, exc_val, exc_tb):
  1338. """
  1339. If this method returns True, it means that the context manager can handle the exception,
  1340. so that the with statement terminates the propagation of the exception
  1341. """
  1342. get_current_session().pop_scope()
  1343. return False # Propagate Exception
  1344. def __call__(self, func):
  1345. """decorator implement"""
  1346. @wraps(func)
  1347. def wrapper(*args, **kwargs):
  1348. self.__enter__()
  1349. try:
  1350. return func(*args, **kwargs)
  1351. finally:
  1352. self.__exit__(None, None, None)
  1353. @wraps(func)
  1354. async def coro_wrapper(*args, **kwargs):
  1355. self.__enter__()
  1356. try:
  1357. return await func(*args, **kwargs)
  1358. finally:
  1359. self.__exit__(None, None, None)
  1360. if iscoroutinefunction(func):
  1361. return coro_wrapper
  1362. else:
  1363. return wrapper