1
0

output.py 68 KB

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