output.py 70 KB

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