output.py 70 KB

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