output.py 68 KB

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