Skip to content

Commit 4fb9b03

Browse files
committed
add pywebio_battery in doc
1 parent ce2a047 commit 4fb9b03

File tree

4 files changed

+13
-219
lines changed

4 files changed

+13
-219
lines changed

docs/battery.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
.. automodule:: pywebio_battery
2+
:members:

docs/cookbook.rst

Lines changed: 3 additions & 219 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
Cookbook
22
==========================
33

4+
.. seealso:: :doc:`PyWebIO Battery <battery>`
5+
46
.. contents::
57
:local:
68

@@ -68,148 +70,7 @@ read the following articles for more information:
6870
* `Embedding in a web application server (Flask) — Matplotlib documentation <https://matplotlib.org/stable/gallery/user_interfaces/web_application_server_sgskip.html>`_
6971

7072

71-
Blocking confirm model
72-
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
73-
74-
The following code uses the lock mechanism to make the button callback function synchronous:
75-
76-
.. collapse:: Click to expand the code
77-
78-
.. exportable-codeblock::
79-
:name: cookbook-confirm-model
80-
:summary: Blocking confirm model
81-
82-
import threading
83-
from pywebio import output
84-
85-
def confirm(title, content=None, timeout=None):
86-
"""Show a confirm model.
87-
88-
:param str title: Model title.
89-
:param list/put_xxx() content: Model content.
90-
:param None/float timeout: Seconds for operation time out.
91-
:return: Return `True` when the "CONFIRM" button is clicked,
92-
return `False` when the "CANCEL" button is clicked,
93-
return `None` when a timeout is given and the operation times out.
94-
"""
95-
if not isinstance(content, list):
96-
content = [content]
97-
98-
event = threading.Event()
99-
result = None
100-
101-
def onclick(val):
102-
nonlocal result
103-
result = val
104-
event.set()
105-
106-
content.append(output.put_buttons([
107-
{'label': 'CONFIRM', 'value': True},
108-
{'label': 'CANCEL', 'value': False, 'color': 'danger'},
109-
], onclick=onclick))
110-
output.popup(title=title, content=content, closable=False)
111-
112-
event.wait(timeout=timeout) # wait the model buttons are clicked
113-
output.close_popup()
114-
return result
115-
116-
117-
res = confirm('Confirm', 'You have 5 seconds to make s choice', timeout=5)
118-
output.put_text("Your choice is:", res)
119-
120-
Input in the popup
121-
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
122-
.. https://github.com/pywebio/PyWebIO/discussions/132
123-
124-
In the following code, we define a ``popup_input()`` function, which can be used to get input in popup:
125-
126-
.. collapse:: Click to expand the code
127-
128-
.. exportable-codeblock::
129-
:name: cookbook-redirect-stdout
130-
:summary: Redirect stdout to PyWebIO
131-
132-
def popup_input(pins, names, title='Please fill out the form'):
133-
"""Show a form in popup window.
134-
135-
:param list pins: pin output list.
136-
:param list pins: pin name list.
137-
:param str title: model title.
138-
:return: return the form as dict, return None when user cancel the form.
139-
"""
140-
if not isinstance(pins, list):
141-
pins = [pins]
142-
143-
from pywebio.utils import random_str
144-
action_name = 'action_' + random_str(10)
145-
146-
pins.append(put_actions(action_name, buttons=[
147-
{'label': 'Submit', 'value': True},
148-
{'label': 'Cancel', 'value': False, 'color': 'danger'},
149-
]))
150-
popup(title=title, content=pins, closable=False)
151-
152-
change_info = pin_wait_change(action_name)
153-
result = None
154-
if change_info['name'] == action_name and change_info['value']:
155-
result = {name: pin[name] for name in names}
156-
close_popup()
157-
return result
158-
159-
160-
from pywebio.pin import put_input
161-
162-
result = popup_input([
163-
put_input('name', label='Input your name'),
164-
put_input('age', label='Input your age', type="number")
165-
], names=['name', 'age'])
166-
put_text(result)
167-
168-
The code uses :doc:`pin module </pin>` to add input widgets to popup window,
169-
and uses the lock mechanism to wait the form buttons to be clicked.
170-
171-
172-
Redirect stdout to PyWebIO application
173-
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
174-
.. https://github.com/pywebio/PyWebIO/discussions/21
175-
176-
The following code shows how to redirect stdout of python code and subprocess to PyWebIO application:
177-
178-
.. collapse:: Click to expand the code
179-
180-
.. exportable-codeblock::
181-
:name: cookbook-redirect-stdout
182-
:summary: Redirect stdout to PyWebIO
183-
184-
import io
185-
import time
186-
import subprocess # ..doc-only
187-
from contextlib import redirect_stdout
188-
189-
# redirect `print()` to pywebio
190-
class WebIO(io.IOBase):
191-
def write(self, content):
192-
put_text(content, inline=True)
193-
194-
with redirect_stdout(WebIO()):
195-
for i in range(10):
196-
print(i, time.time())
197-
time.sleep(0.2)
198-
199-
## ----
200-
import subprocess # ..demo-only
201-
# redirect a subprocess' stdout to pywebio
202-
process = subprocess.Popen("ls -ahl", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
203-
while True:
204-
output = process.stdout.readline()
205-
if output:
206-
put_text(output.decode('utf8'), inline=True)
207-
208-
if not output and process.poll() is not None:
209-
break
210-
211-
212-
Add missing syntax highlight for code output
73+
Add new syntax highlight for code output
21374
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
21475

21576
When output code via `put_markdown()` or `put_code()`, PyWebIO provides syntax highlight for some common languages.
@@ -241,21 +102,6 @@ If you find your code have no syntax highlight, you can add the syntax highlight
241102
Web application related
242103
----------------------------------------------------------------------------------------------
243104

244-
Get URL parameters of current page
245-
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
246-
247-
You can use URL parameter (known also as "query strings" or "URL query parameters") to pass information to your web
248-
application. In PyWebIO application, you can use the following code to get the URL parameters as a Python dict.
249-
250-
.. exportable-codeblock::
251-
:name: cookbook-url-query
252-
:summary: Get URL parameters of current page
253-
254-
# `query` is a dict
255-
query = eval_js("Object.fromEntries(new URLSearchParams(window.location.search))")
256-
put_text(query)
257-
258-
259105
Add Google AdSense/Analytics code
260106
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
261107

@@ -287,65 +133,3 @@ Add the following code to the beginning of your PyWebIO application main functio
287133

288134
session.run_js('WebIO._state.CurrentSession.on_session_close(()=>{setTimeout(()=>location.reload(), 4000})')
289135

290-
Cookie and localStorage manipulation
291-
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
292-
.. https://github.com/pywebio/PyWebIO/discussions/99
293-
294-
You can use `pywebio.session.run_js()` and `pywebio.session.eval_js()` to deal with cookies or localStorage with js.
295-
296-
``localStorage`` manipulation:
297-
298-
.. exportable-codeblock::
299-
:name: cookbook-localStorage
300-
:summary: ``localStorage`` manipulation
301-
302-
set_localstorage = lambda key, value: run_js("localStorage.setItem(key, value)", key=key, value=value)
303-
get_localstorage = lambda key: eval_js("localStorage.getItem(key)", key=key)
304-
305-
set_localstorage('hello', 'world')
306-
val = get_localstorage('hello')
307-
put_text(val)
308-
309-
310-
Cookie manipulation:
311-
312-
.. collapse:: Click to expand the code
313-
314-
.. exportable-codeblock::
315-
:name: cookbook-cookie
316-
:summary: Cookie manipulation
317-
318-
# https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript
319-
run_js("""
320-
window.setCookie = function(name,value,days) {
321-
var expires = "";
322-
if (days) {
323-
var date = new Date();
324-
date.setTime(date.getTime() + (days*24*60*60*1000));
325-
expires = "; expires=" + date.toUTCString();
326-
}
327-
document.cookie = name + "=" + (value || "") + expires + "; path=/";
328-
}
329-
window.getCookie = function(name) {
330-
var nameEQ = name + "=";
331-
var ca = document.cookie.split(';');
332-
for(var i=0;i < ca.length;i++) {
333-
var c = ca[i];
334-
while (c.charAt(0)==' ') c = c.substring(1,c.length);
335-
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
336-
}
337-
return null;
338-
}
339-
""")
340-
341-
def setcookie(key, value, days=0):
342-
run_js("setCookie(key, value, days)", key=key, value=value, days=days)
343-
344-
def getcookie(key):
345-
return eval_js("getCookie(key)", key=key)
346-
347-
setcookie('hello', 'world')
348-
val = getcookie('hello')
349-
put_text(val)
350-
351-

docs/index.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,12 @@ This documentation is also available in `PDF and Epub formats <https://readthedo
9696
cookbook
9797
releases
9898

99+
.. toctree::
100+
:maxdepth: 2
101+
:caption: Battery
102+
103+
battery
104+
99105
.. toctree::
100106
:maxdepth: 2
101107
:caption: Implement Doc

requirements.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ sphinx==3.*
2525
sphinx-tabs
2626
sphinx-rtd-theme==0.4.*
2727
sphinx-toolbox==2.15.0
28+
sphinx-intl
29+
git+https://github.com/wang0618/pywebio-battery.git
2830

2931
# demo running requirements
3032
numpy

0 commit comments

Comments
 (0)