cookbook.rst 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. Cookbook
  2. ==========================
  3. .. seealso:: :doc:`PyWebIO Battery <battery>`
  4. .. contents::
  5. :local:
  6. Interaction related
  7. ----------------------------------------------------------------------------------------------
  8. Equivalent to "Press any key to continue"
  9. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  10. .. exportable-codeblock::
  11. :name: cookbook-press-anykey-continue
  12. :summary: Press any key to continue
  13. actions(buttons=["Continue"])
  14. put_text("Go next") # ..demo-only
  15. Output pandas dataframe
  16. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  17. .. exportable-codeblock::
  18. :name: cookbook-pandas-df
  19. :summary: Output pandas dataframe
  20. import numpy as np
  21. import pandas as pd
  22. df = pd.DataFrame(np.random.randn(6, 4), columns=list("ABCD"))
  23. put_html(df.to_html(border=0))
  24. .. seealso:: `pandas.DataFrame.to_html — pandas documentation <https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_html.html#pandas-dataframe-to-html>`_
  25. Output Matplotlib figure
  26. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  27. Instead of using ``matplotlib.pyplot.show()``, to show matplotlib figure in PyWebIO, you need to save the figure to in-memory buffer fist and then output the buffer
  28. via :func:`pywebio.output.put_image`:
  29. .. exportable-codeblock::
  30. :name: cookbook-matplotlib
  31. :summary: Output Matplotlib plot
  32. import matplotlib
  33. import matplotlib.pyplot as plt
  34. import io
  35. import pywebio
  36. matplotlib.use('agg') # required, use a non-interactive backend
  37. fig, ax = plt.subplots() # Create a figure containing a single axes.
  38. ax.plot([1, 2, 3, 4], [1, 4, 2, 3]) # Plot some data on the axes.
  39. buf = io.BytesIO()
  40. fig.savefig(buf)
  41. pywebio.output.put_image(buf.getvalue())
  42. The ``matplotlib.use('agg')`` is required so that the server does not try to create (and then destroy) GUI windows
  43. that will never be seen.
  44. When using Matplotlib in a web server (multiple threads environment), pyplot may cause some conflicts in some cases,
  45. read the following articles for more information:
  46. * `Multi Threading in Python and Pyplot | by Ranjitha Korrapati | Medium <https://medium.com/@ranjitha.korrapati/multi-threading-in-python-and-pyplot-46f325e6a9d0>`_
  47. * `Embedding in a web application server (Flask) — Matplotlib documentation <https://matplotlib.org/stable/gallery/user_interfaces/web_application_server_sgskip.html>`_
  48. Add new syntax highlight for code output
  49. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  50. When output code via `put_markdown()` or `put_code()`, PyWebIO provides syntax highlight for some common languages.
  51. If you find your code have no syntax highlight, you can add the syntax highlighter by two following steps:
  52. 1. Go to `prismjs CDN page <https://www.jsdelivr.com/package/npm/prismjs?version=1.23.0&path=components>`_ to get your syntax highlighter link.
  53. 2. Use :func:`config(js_file=...) <pywebio.config>` to load the syntax highlight module
  54. ::
  55. @config(js_file="https://cdn.jsdelivr.net/npm/prismjs@1.23.0/components/prism-diff.min.js")
  56. def main():
  57. put_code("""
  58. + AAA
  59. - BBB
  60. CCC
  61. """.strip(), language='diff')
  62. put_markdown("""
  63. ```diff
  64. + AAA
  65. - BBB
  66. CCC
  67. ```
  68. """, lstrip=True)
  69. Web application related
  70. ----------------------------------------------------------------------------------------------
  71. Add Google AdSense/Analytics code
  72. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  73. When you setup Google AdSense/Analytics, you will get a javascript file and a piece of code that needs to be inserted
  74. into your application page, you can use :func:`pywebio.config()` to inject js file and code to your PyWebIO application::
  75. from pywebio import start_server, output, config
  76. js_file = "https://www.googletagmanager.com/gtag/js?id=G-xxxxxxx"
  77. js_code = """
  78. window.dataLayer = window.dataLayer || [];
  79. function gtag(){dataLayer.push(arguments);}
  80. gtag('js', new Date());
  81. gtag('config', 'G-xxxxxxx');
  82. """
  83. @config(js_file=js_file, js_code=js_code)
  84. def main():
  85. output.put_text("hello world")
  86. start_server(main, port=8080)
  87. Refresh page on connection lost
  88. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  89. Add the following code to the beginning of your PyWebIO application main function::
  90. session.run_js('WebIO._state.CurrentSession.on_session_close(()=>{setTimeout(()=>location.reload(), 4000})')