1
0

output.py 91 KB

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