|
| 1 | +Cookbook |
| 2 | +========================== |
| 3 | + |
| 4 | +.. contents:: |
| 5 | + :local: |
| 6 | + |
| 7 | +Interaction related |
| 8 | +---------------------------------------------------------------------------------------------- |
| 9 | + |
| 10 | +Equivalent to "Press any key to continue" |
| 11 | +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 12 | + |
| 13 | +.. exportable-codeblock:: |
| 14 | + :name: cookbook-press-anykey-continue |
| 15 | + :summary: Press any key to continue |
| 16 | + |
| 17 | + actions(buttons=["Continue"]) |
| 18 | + put_text("Go next") # ..demo-only |
| 19 | + |
| 20 | + |
| 21 | +Output pandas dataframe |
| 22 | +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 23 | + |
| 24 | +.. exportable-codeblock:: |
| 25 | + :name: cookbook-pandas-df |
| 26 | + :summary: Output pandas dataframe |
| 27 | + |
| 28 | + import numpy as np |
| 29 | + import pandas as pd |
| 30 | + |
| 31 | + df = pd.DataFrame(np.random.randn(6, 4), columns=list("ABCD")) |
| 32 | + put_html(df.to_html(border=0)) |
| 33 | + |
| 34 | +.. seealso:: `pandas.DataFrame.to_html — pandas documentation <https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_html.html#pandas-dataframe-to-html>`_ |
| 35 | + |
| 36 | +Output Matplotlib figure |
| 37 | +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 38 | + |
| 39 | +Simply do not call ``matplotlib.pyplot.show``, directly save the figure to in-memory buffer and output the buffer |
| 40 | +via :func:`pywebio.output.put_image`: |
| 41 | + |
| 42 | +.. exportable-codeblock:: |
| 43 | + :name: cookbook-matplotlib |
| 44 | + :summary: Output Matplotlib plot |
| 45 | + |
| 46 | + import matplotlib |
| 47 | + import matplotlib.pyplot as plt |
| 48 | + import io |
| 49 | + import pywebio |
| 50 | + |
| 51 | + matplotlib.use('agg') # required, use a non-interactive backend |
| 52 | + |
| 53 | + fig, ax = plt.subplots() # Create a figure containing a single axes. |
| 54 | + ax.plot([1, 2, 3, 4], [1, 4, 2, 3]) # Plot some data on the axes. |
| 55 | + |
| 56 | + buf = io.BytesIO() |
| 57 | + fig.savefig(buf) |
| 58 | + pywebio.output.put_image(buf.getvalue()) |
| 59 | + |
| 60 | +The ``matplotlib.use('agg')`` is required so that the server does not try to create (and then destroy) GUI windows |
| 61 | +that will never be seen. |
| 62 | + |
| 63 | +When using Matplotlib in a web server (multiple threads environment), pyplot may cause some conflicts in some cases, |
| 64 | +read the following articles for more information: |
| 65 | + |
| 66 | + * `Multi Threading in Python and Pyplot | by Ranjitha Korrapati | Medium <https://medium.com/@ranjitha.korrapati/multi-threading-in-python-and-pyplot-46f325e6a9d0>`_ |
| 67 | + |
| 68 | + * `Embedding in a web application server (Flask) — Matplotlib documentation <https://matplotlib.org/stable/gallery/user_interfaces/web_application_server_sgskip.html>`_ |
| 69 | + |
| 70 | + |
| 71 | +Blocking confirm model |
| 72 | +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 73 | + |
| 74 | +.. collapse:: Code |
| 75 | + |
| 76 | + .. exportable-codeblock:: |
| 77 | + :name: cookbook-confirm-model |
| 78 | + :summary: Blocking confirm model |
| 79 | + |
| 80 | + import threading |
| 81 | + from pywebio import output |
| 82 | + |
| 83 | + def confirm(title, content=None, timeout=None): |
| 84 | + """Show a confirm model. |
| 85 | + |
| 86 | + :param str title: Model title. |
| 87 | + :param list/put_xxx() content: Model content. |
| 88 | + :param None/float timeout: Seconds for operation time out. |
| 89 | + :return: Return `True` when the "CONFIRM" button is clicked, |
| 90 | + return `False` when the "CANCEL" button is clicked, |
| 91 | + return `None` when a timeout is given and the operation times out. |
| 92 | + """ |
| 93 | + if not isinstance(content, list): |
| 94 | + content = [content] |
| 95 | + |
| 96 | + event = threading.Event() |
| 97 | + result = None |
| 98 | + |
| 99 | + def onclick(val): |
| 100 | + nonlocal result |
| 101 | + result = val |
| 102 | + event.set() |
| 103 | + |
| 104 | + content.append(output.put_buttons([ |
| 105 | + {'label': 'CONFIRM', 'value': True}, |
| 106 | + {'label': 'CANCEL', 'value': False, 'color': 'danger'}, |
| 107 | + ], onclick=onclick)) |
| 108 | + output.popup(title=title, content=content, closable=False) |
| 109 | + |
| 110 | + event.wait(timeout=timeout) # wait the model buttons are clicked |
| 111 | + output.close_popup() |
| 112 | + return result |
| 113 | + |
| 114 | + |
| 115 | + res = confirm('Confirm', 'You have 5 seconds to make s choice', timeout=5) |
| 116 | + output.put_text("Your choice is:", res) |
| 117 | + |
| 118 | + |
| 119 | + |
| 120 | +Web application related |
| 121 | +---------------------------------------------------------------------------------------------- |
| 122 | + |
| 123 | +Get URL parameters of current page |
| 124 | +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 125 | + |
| 126 | +You can use URL parameter (known also as "query strings" or "URL query parameters") to pass information to your web |
| 127 | +application. In PyWebIO application, you can use the following code to get the URL parameters as a Python dict. |
| 128 | + |
| 129 | +.. exportable-codeblock:: |
| 130 | + :name: cookbook-url-query |
| 131 | + :summary: Get URL parameters of current page |
| 132 | + |
| 133 | + # `query` is a dict |
| 134 | + query = eval_js("Object.fromEntries(new URLSearchParams(window.location.search))") |
| 135 | + put_text(query) |
| 136 | + |
| 137 | + |
| 138 | +Add Google AdSense/Analytics code |
| 139 | +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 140 | + |
| 141 | +When you setup Google AdSense/Analytics, you will get a javascript file and a piece of code that needs to be inserted |
| 142 | +into your application page, you can use :func:`pywebio.config()` to inject js file and code to your PyWebIO application:: |
| 143 | + |
| 144 | + from pywebio import start_server, output, config |
| 145 | + |
| 146 | + js_file = "https://www.googletagmanager.com/gtag/js?id=G-xxxxxxx" |
| 147 | + js_code = """ |
| 148 | + window.dataLayer = window.dataLayer || []; |
| 149 | + function gtag(){dataLayer.push(arguments);} |
| 150 | + gtag('js', new Date()); |
| 151 | + |
| 152 | + gtag('config', 'G-xxxxxxx'); |
| 153 | + """ |
| 154 | + |
| 155 | + @config(js_file=js_file, js_code=js_code) |
| 156 | + def main(): |
| 157 | + output.put_text("hello world") |
| 158 | + |
| 159 | + start_server(main, port=8080) |
| 160 | + |
| 161 | + |
| 162 | +Refresh page on connection lost |
| 163 | +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 164 | + |
| 165 | +Add the following code to the beginning of your PyWebIO application main function:: |
| 166 | + |
| 167 | + session.run_js('WebIO._state.CurrentSession.on_session_close(()=>{setTimeout(()=>location.reload(), 4000})') |
| 168 | + |
0 commit comments