mirror of
https://github.com/pyscript/pyscript.git
synced 2026-03-01 08:05:29 -05:00
Update docs examples so they don't use deprecated features, styling tweaks (#982)
* Deprecate pyscript output attribute * Update code blocks so they work * Small tweaks to styling and use html to warning * Fix broken test from bad conflict resolution * lowercase pyodide
This commit is contained in:
@@ -26,5 +26,5 @@ showWarning(`
|
||||
<p>
|
||||
The <code>py-deprecated</code> tag is deprecated. Please use the <code>py-actual</code> tag instead. Please refer to <a href="#">this documentation page</a> for more information.
|
||||
</p>
|
||||
`)
|
||||
`, "html")
|
||||
```
|
||||
|
||||
@@ -14,14 +14,18 @@ from `PyScript` using Python, since currently, the common tools such as `request
|
||||
|
||||
The `fetch` API is a modern way to make HTTP requests. It is available in all modern browsers, and in Pyodide.
|
||||
|
||||
Although there are two ways to use `fetch`, 1) using `JavaScript` from `PyScript`, and 2) using Pyodide's Python wrapper,
|
||||
`Pyodide.http.pyfetch`, this example will only show how to use the Python wrapper. Still, the
|
||||
Although there are two ways to use `fetch`:
|
||||
1) using `JavaScript` from `PyScript`
|
||||
2) using Pyodide's Python wrapper,
|
||||
`pyodide.http.pyfetch`
|
||||
|
||||
This example will only show how to use the Python wrapper. Still, the
|
||||
[fetch documentation](https://developer.mozilla.org/en-US/docs/Web/API/fetch#parameters) is a useful reference, as its
|
||||
parameters can be called from Python using the `pyfetch` wrapper.
|
||||
|
||||
## Pyodide.http, pyfetch, and FetchResponse
|
||||
|
||||
[Pyodide.http module](https://pyodide.org/en/stable/usage/api/python-api/http.html#module-pyodide.http) is a Python API
|
||||
The [pyodide.http module](https://pyodide.org/en/stable/usage/api/python-api/http.html#module-pyodide.http) is a Python API
|
||||
for dealing with HTTP requests. It provides the `pyfetch` function as a wrapper for the `fetch` API,
|
||||
which returns a `FetchResponse` object whenever a request is made. Extra keyword arguments can be passed to `pyfetch`
|
||||
which will be passed to the `fetch` API.
|
||||
@@ -92,9 +96,9 @@ concluding html code.
|
||||
<title>GET, POST, PUT, DELETE example</title>
|
||||
|
||||
<link rel="icon" type="image/png" href="favicon.png" />
|
||||
<link rel="stylesheet" href="../build/pyscript.css" />
|
||||
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
|
||||
|
||||
<script defer src="../build/pyscript.js"></script>
|
||||
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
|
||||
<py-config>
|
||||
[[fetch]]
|
||||
files = ["/request.py"]
|
||||
@@ -106,34 +110,33 @@ concluding html code.
|
||||
Here is the output of your request:
|
||||
</p>
|
||||
<py-script>
|
||||
```
|
||||
```python
|
||||
import asyncio # important!!
|
||||
import json
|
||||
from request import request # import our request function.
|
||||
import asyncio
|
||||
import json
|
||||
from request import request # import our request function.
|
||||
|
||||
baseurl = "https://jsonplaceholder.typicode.com/"
|
||||
async def main():
|
||||
baseurl = "https://jsonplaceholder.typicode.com"
|
||||
|
||||
# GET
|
||||
headers = {"Content-type": "application/json"}
|
||||
response = await request(baseurl+"posts/2", method="GET", headers=headers)
|
||||
print(f"GET request=> status:{response.status}, json:{await response.json()}")
|
||||
# GET
|
||||
headers = {"Content-type": "application/json"}
|
||||
response = await request(f"{baseurl}/posts/2", method="GET", headers=headers)
|
||||
print(f"GET request=> status:{response.status}, json:{await response.json()}")
|
||||
|
||||
# POST
|
||||
body = json.dumps({"title": "test_title", "body": "test body", "userId": 1})
|
||||
new_post = await request(baseurl+"posts", body=body, method="POST", headers=headers)
|
||||
print(f"POST request=> status:{new_post.status}, json:{await new_post.json()}")
|
||||
# POST
|
||||
body = json.dumps({"title": "test_title", "body": "test body", "userId": 1})
|
||||
new_post = await request(f"{baseurl}/posts", body=body, method="POST", headers=headers)
|
||||
print(f"POST request=> status:{new_post.status}, json:{await new_post.json()}")
|
||||
|
||||
# PUT
|
||||
body = json.dumps({"id": 1, "title": "test_title", "body": "test body", "userId": 2})
|
||||
new_post = await request(baseurl+"posts/1", body=body, method="PUT", headers=headers)
|
||||
print(f"PUT request=> status:{new_post.status}, json:{await new_post.json()}")
|
||||
# PUT
|
||||
body = json.dumps({"id": 1, "title": "test_title", "body": "test body", "userId": 2})
|
||||
new_post = await request(f"{baseurl}/posts/1", body=body, method="PUT", headers=headers)
|
||||
print(f"PUT request=> status:{new_post.status}, json:{await new_post.json()}")
|
||||
|
||||
# DELETE
|
||||
new_post = await request(baseurl+"posts/1", method="DELETE", headers=headers)
|
||||
print(f"DELETE request=> status:{new_post.status}, json:{await new_post.json()}")
|
||||
```
|
||||
```html
|
||||
# DELETE
|
||||
new_post = await request(f"{baseurl}/posts/1", method="DELETE", headers=headers)
|
||||
print(f"DELETE request=> status:{new_post.status}, json:{await new_post.json()}")
|
||||
|
||||
asyncio.ensure_future(main())
|
||||
</py-script>
|
||||
|
||||
<div>
|
||||
@@ -195,7 +198,7 @@ await pyodide.http.pyfetch(url: str, **kwargs: Any) -> FetchResponse
|
||||
```
|
||||
Use `pyfetch` to make HTTP requests in `PyScript`. This is a wrapper around the `fetch` API. Returns a `FetchResponse`.
|
||||
|
||||
### [`pyfetch` Docs.](https://pyodide.org/en/stable/usage/api/python-api/http.html#pyodide.http.pyfetch)
|
||||
- [`pyfetch` Docs.](https://pyodide.org/en/stable/usage/api/python-api/http.html#pyodide.http.pyfetch)
|
||||
|
||||
## pyodide.http.FetchResponse
|
||||
### Usage
|
||||
@@ -207,4 +210,4 @@ json = await response.json()
|
||||
Class for handling HTTP responses. This is a wrapper around the `JavaScript` fetch `Response`. Contains common (async)
|
||||
methods and properties for handling HTTP responses, such as `json()`, `url`, `status`, `headers`, etc.
|
||||
|
||||
### [`FetchResponse` Docs.](https://pyodide.org/en/stable/usage/api/python-api/http.html#pyodide.http.FetchResponse)
|
||||
- [`FetchResponse` Docs.](https://pyodide.org/en/stable/usage/api/python-api/http.html#pyodide.http.FetchResponse)
|
||||
|
||||
@@ -45,7 +45,7 @@ The [PyScript JavaScript module](../reference/modules/pyscript.md) exposes its
|
||||
<button onclick="showX()">Click Me to Get 'x' from Python</button>
|
||||
<script>
|
||||
function showX(){
|
||||
console.log(`In Python right now, x = ${PyScript.globals.get('x')}`)
|
||||
console.log(`In Python right now, x = ${pyscript.runtime.globals.get('x')}`)
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
@@ -59,7 +59,7 @@ Since [everything is an object](https://docs.python.org/3/reference/datamodel.ht
|
||||
<button onclick="sortInPython(['Candy', 'Donut', 'Apple', 'Banana'])">Sort In Python And Log</button>
|
||||
<script>
|
||||
function sortInPython(data){
|
||||
js_sorted = PyScript.runtime.globals.get('sorted') //grab python's 'sorted' function
|
||||
js_sorted = pyscript.runtime.globals.get('sorted') //grab python's 'sorted' function
|
||||
const sorted_data = js_sorted(data) //apply the function to the 'data' argument
|
||||
for (const item of sorted_data){
|
||||
console.log(item)
|
||||
@@ -119,7 +119,7 @@ This will make all Python global variables available in JavaScript with `pyodide
|
||||
self.radius = radius
|
||||
|
||||
@property
|
||||
def area:
|
||||
def area(self):
|
||||
return symbols['pi'] * self.radius**2
|
||||
</py-script>
|
||||
```
|
||||
@@ -129,13 +129,72 @@ This will make all Python global variables available in JavaScript with `pyodide
|
||||
<script>
|
||||
document.getElementById("do-math").addEventListener("click", () => {
|
||||
const exp = pyodideGlobals.get('rough_exponential');
|
||||
console.log("e squared is about ${exp(2)}");
|
||||
console.log(`e squared is about ${exp(2)}`);
|
||||
const c = pyodideGlobals.get('Circle')(4);
|
||||
console.log("The area of c is ${c.area}");
|
||||
console.log(`The area of c is ${c.area}`);
|
||||
});
|
||||
</script>
|
||||
```
|
||||
|
||||
#### Full example
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
|
||||
<title>Exporting all Global Python Objects</title>
|
||||
|
||||
<link rel="icon" type="image/png" href="favicon.png" />
|
||||
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
|
||||
|
||||
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<input type="button" value="Log Python Variables" id="do-math">
|
||||
<py-script>
|
||||
from js import createObject
|
||||
from pyodide.ffi import create_proxy
|
||||
|
||||
createObject(create_proxy(globals()), "pyodideGlobals")
|
||||
|
||||
# create some Python objects:
|
||||
symbols = {'pi': 3.1415926, 'e': 2.7182818}
|
||||
|
||||
def rough_exponential(x):
|
||||
return symbols['e']**x
|
||||
|
||||
class Circle():
|
||||
def __init__(self, radius):
|
||||
self.radius = radius
|
||||
|
||||
@property
|
||||
def area(self):
|
||||
return symbols['pi'] * self.radius**2
|
||||
</py-script>
|
||||
<script>
|
||||
function createObject(object, variableName){
|
||||
//Bind a variable whose name is the string variableName
|
||||
// to the object called 'object'
|
||||
let execString = variableName + " = object"
|
||||
console.log("Running '" + execString + "'");
|
||||
eval(execString)
|
||||
}
|
||||
|
||||
document.getElementById("do-math").addEventListener("click", () => {
|
||||
const exp = pyodideGlobals.get('rough_exponential');
|
||||
console.log(`e squared is about ${exp(2)}`);
|
||||
const c = pyodideGlobals.get('Circle')(4);
|
||||
console.log(`The area of c is ${c.area}`);
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
|
||||
### Exporting Individual Python Objects
|
||||
|
||||
@@ -175,3 +234,62 @@ We can also export individual Python objects to the JavaScript global scope if w
|
||||
});
|
||||
</script>
|
||||
```
|
||||
|
||||
#### Full example
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
|
||||
<title>Exporting Individual Python Objects</title>
|
||||
|
||||
<link rel="icon" type="image/png" href="favicon.png" />
|
||||
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
|
||||
|
||||
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<py-script>
|
||||
import js
|
||||
from pyodide.ffi import create_proxy
|
||||
|
||||
# Create 3 python objects
|
||||
language = "Python 3"
|
||||
animals = ['dog', 'cat', 'bird']
|
||||
multiply3 = lambda a, b, c: a * b * c
|
||||
|
||||
# js object can be named the same as Python objects...
|
||||
js.createObject(language, "language")
|
||||
|
||||
# ...but don't have to be
|
||||
js.createObject(create_proxy(animals), "animals_from_py")
|
||||
|
||||
# functions are objects too, in both Python and Javascript
|
||||
js.createObject(create_proxy(multiply3), "multiply")
|
||||
</py-script>
|
||||
|
||||
<input type="button" value="Log Python Variables" id="log-python-variables">
|
||||
<script>
|
||||
function createObject(object, variableName){
|
||||
//Bind a variable whose name is the string variableName
|
||||
// to the object called 'object'
|
||||
let execString = variableName + " = object"
|
||||
console.log("Running '" + execString + "'");
|
||||
eval(execString)
|
||||
}
|
||||
|
||||
document.getElementById("log-python-variables").addEventListener("click", () => {
|
||||
console.log(`Nice job using ${language}`);
|
||||
for (const animal of animals_from_py){
|
||||
console.log(`Do you like ${animal}s? `);
|
||||
}
|
||||
console.log(`2 times 3 times 4 is ${multiply(2,3,4)}`);
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#### `display(*values, target=None, append=True)`
|
||||
# `display(*values, target=None, append=True)`
|
||||
|
||||
**Parameters:**
|
||||
## Parameters
|
||||
|
||||
`*values` - the objects to be displayed. String objects are output as-written. For non-string objects, the default content to display is the the object's `repr()`. Objects may implement the following methods to indicate that they should be displayed as a different MIME type. MIME types with a * indicate that the content will be wrapped in the appropriate html tags and attributes before output:
|
||||
|
||||
@@ -21,13 +21,13 @@
|
||||
|
||||
`append` - `boolean` if the output is going to be appended or not to the `target`ed element. It creates a `<div>` tag if `True` and a `<py-script>` tag with a random ID if `False`. The default value for `append` is `True`.
|
||||
|
||||
**Description:**
|
||||
### Description
|
||||
|
||||
Display is the default function to display objects on the screen. Functions like the Python `print()` or JavaScript `console.log()` are now defaulted to only appear on the terminal.
|
||||
|
||||
Display will throw an exception if the target is not clear. E.g. the following code is invalid:
|
||||
|
||||
```
|
||||
```html
|
||||
<py-script>
|
||||
def display_hello():
|
||||
# this fails because we don't have any implicit target
|
||||
@@ -39,4 +39,15 @@ Display will throw an exception if the target is not clear. E.g. the following c
|
||||
|
||||
Because it's considered unclear if the `hello` string should be displayed underneath the `<py-script>` tag or the `<button>` tag.
|
||||
|
||||
To write compliant code, make sure to specify the target using the `target` parameter.
|
||||
To write compliant code, make sure to specify the target using the `target` parameter, for example:
|
||||
|
||||
```html
|
||||
<py-script>
|
||||
def display_hello():
|
||||
# this fails because we don't have any implicit target
|
||||
# from event handlers
|
||||
display('hello', target="helloDiv")
|
||||
</py-script>
|
||||
<div id="helloDiv"></div>
|
||||
<button id="my-button" py-onClick="display_hello()">Click me</button>
|
||||
```
|
||||
|
||||
@@ -8,9 +8,9 @@ version_info(year=2023, month=2, minor=1, releaselevel='dev')
|
||||
```
|
||||
|
||||
## Version Fields
|
||||
| **parameter** | **CalVer equivalent field** | **example value** | **description** |
|
||||
|---------------|-------------------------|---------------|------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `year` | Full year (YYYY) | 2023 | The year of the release; when printed or represented as a string, always written with 4 digits |
|
||||
| `month` | Short Month (MM) | 2 | The month of the release; when printed or represented as a string, written with 1 or 2 digits as necessary |
|
||||
| `minor` | | 1 | The incremental number of the release for this month; when printed or represented as a string, written with 1 or two digits as necessary |
|
||||
| `releaselevel` | | 'dev' | A string representing the qualifications of this build. |
|
||||
| **parameter** | **CalVer equivalent field** | **example value** | **description** |
|
||||
|-----------------|-----------------------------|---------------|------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `year` | Full year (YYYY) | 2023 | The year of the release; when printed or represented as a string, always written with 4 digits |
|
||||
| `month` | Short Month (MM) | 2 | The month of the release; when printed or represented as a string, written with 1 or 2 digits as necessary |
|
||||
| `minor` | | 1 | The incremental number of the release for this month; when printed or represented as a string, written with 1 or two digits as necessary |
|
||||
| `releaselevel` | | 'dev' | A string representing the qualifications of this build |
|
||||
|
||||
@@ -8,10 +8,10 @@ The `<py-config>` element should be placed within the `<body>` element.
|
||||
|
||||
## Attributes
|
||||
|
||||
| attribute | type | default | description |
|
||||
|----|----|----|----|
|
||||
| **type** | string | "toml" | Syntax type of the `<py-config>`. Value can be `json` or `toml`. Default: "toml" if type is unspecifed. |
|
||||
| **src** | url | | Source url to an external configuration file. |
|
||||
| attribute | type | default | description |
|
||||
|-----------|--------|---------|---------------------------------------------------------------------------------------------------------|
|
||||
| **type** | string | "toml" | Syntax type of the `<py-config>`. Value can be `json` or `toml`. Default: "toml" if type is unspecifed. |
|
||||
| **src** | url | | Source url to an external configuration file. |
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -251,12 +251,13 @@ The following optional values are supported by `<py-config>`:
|
||||
### <a name="fetch">Fetch</a>
|
||||
|
||||
A fetch configuration consists of the following:
|
||||
| Value | Type | Description |
|
||||
| ----- | ---- | ----------- |
|
||||
| `from` | string | Base URL for the resource to be fetched. |
|
||||
| `to_folder` | string | Name of the folder to create in the filesystem. |
|
||||
| `to_file` | string | Name of the target to create in the filesystem. |
|
||||
| `files` | List of strings | List of files to be downloaded. |
|
||||
|
||||
| Value | Type | Description |
|
||||
|--------------|-----------------|-------------------------------------------------|
|
||||
| `from` | string | Base URL for the resource to be fetched. |
|
||||
| `to_folder` | string | Name of the folder to create in the filesystem. |
|
||||
| `to_file` | string | Name of the target to create in the filesystem. |
|
||||
| `files` | List of strings | List of files to be downloaded. |
|
||||
|
||||
The parameters `to_file` and `files` shouldn't be supplied together.
|
||||
|
||||
@@ -440,11 +441,11 @@ content/
|
||||
### Runtime
|
||||
|
||||
A runtime configuration consists of the following:
|
||||
| Value | Type | Description |
|
||||
| ----- | ---- | ----------- |
|
||||
| `src` | string (Required) | URL to the runtime source. |
|
||||
| `name` | string | Name of the runtime. This field can be any string and is to be used by the application author for their own customization purposes |
|
||||
| `lang` | string | Programming language supported by the runtime. This field can be used by the application author to provide clarification. It currently has no implications on how PyScript behaves. |
|
||||
| Value | Type | Description |
|
||||
|--------|-------------------|-------------|
|
||||
| `src` | string (Required) | URL to the runtime source. |
|
||||
| `name` | string | Name of the runtime. This field can be any string and is to be used by the application author for their own customization purposes |
|
||||
| `lang` | string | Programming language supported by the runtime. This field can be used by the application author to provide clarification. It currently has no implications on how PyScript behaves. |
|
||||
|
||||
#### Example
|
||||
|
||||
|
||||
@@ -4,14 +4,27 @@ The `<py-repl>` element provides a REPL(Read Eval Print Loop) to evaluate multi-
|
||||
|
||||
## Attributes
|
||||
|
||||
| attribute | type | default | description |
|
||||
|----|----|----|----|
|
||||
| **auto-generate** | boolean | | Auto-generates REPL after evaluation. |
|
||||
| **output** | string | |The element to write output into |
|
||||
| attribute | type | default | description |
|
||||
|-------------------|---------|---------|---------------------------------------|
|
||||
| **auto-generate** | boolean | | Auto-generates REPL after evaluation |
|
||||
| **output** | string | | The element to write output into |
|
||||
|
||||
## Examples
|
||||
### Examples
|
||||
|
||||
#### `<py-repl>` element set to auto-generate
|
||||
|
||||
- `<py-repl>` element set to auto-generate
|
||||
```html
|
||||
<py-repl auto-generate="true"> </py-repl>
|
||||
```
|
||||
|
||||
#### `<py-repl>` element with output
|
||||
|
||||
```html
|
||||
<div id="replOutput"></div>
|
||||
<py-repl output="replOutput">
|
||||
hello = "Hello world!"
|
||||
hello
|
||||
</py-repl>
|
||||
```
|
||||
|
||||
Note that if we `print` any element in the repl, the output will be printed in the [`py-terminal`](../plugins/py-terminal.md) if is enabled.
|
||||
|
||||
@@ -4,13 +4,13 @@ The `<py-script>` element lets you execute multi-line Python scripts both inline
|
||||
|
||||
## Attributes
|
||||
|
||||
| attribute | type | default | description |
|
||||
|----|----|----|----|
|
||||
| **src** | url | | Url to a python source file. |
|
||||
| attribute | type | default | description |
|
||||
|-----------|------|---------|------------------------------|
|
||||
| **src** | url | | Url of a python source file. |
|
||||
|
||||
## Examples
|
||||
|
||||
### Inline `<py-script>` element:
|
||||
### Inline `<py-script>` element
|
||||
|
||||
Let's execute this multi-line Python script to compute π and print it back onto the page
|
||||
|
||||
@@ -37,7 +37,7 @@ Let's execute this multi-line Python script to compute π and print it back onto
|
||||
</html>
|
||||
```
|
||||
|
||||
### Using `<py-script>` element with `src` attribute:
|
||||
### Using `<py-script>` element with `src` attribute
|
||||
|
||||
we can also move our python code to its own file and reference it via the `src` attribute.
|
||||
|
||||
|
||||
@@ -63,7 +63,7 @@ A proxy for the runtime's `globals()` dictionary. For example:
|
||||
<button onclick="showX()">Click Me to Get 'x' from Python</button>
|
||||
<script>
|
||||
function showX(){
|
||||
console.log(`In Python right now, x = ${PyScript.runtime.globals.get('x')}`)
|
||||
console.log(`In Python right now, x = ${pyscript.runtime.globals.get('x')}`)
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
|
||||
@@ -29,7 +29,7 @@ export class SplashscreenPlugin extends Plugin {
|
||||
|
||||
if ('autoclose_loader' in config) {
|
||||
this.autoclose = config.autoclose_loader;
|
||||
showWarning(AUTOCLOSE_LOADER_DEPRECATED);
|
||||
showWarning(AUTOCLOSE_LOADER_DEPRECATED, "html");
|
||||
}
|
||||
|
||||
if (config.splashscreen) {
|
||||
|
||||
@@ -326,6 +326,8 @@ textarea {
|
||||
min-height: 10em;
|
||||
background-color: black;
|
||||
color: white;
|
||||
padding: 0.5rem;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.py-terminal-hidden {
|
||||
|
||||
@@ -69,7 +69,7 @@ class TestSplashscreen(PyScriptTest):
|
||||
""",
|
||||
)
|
||||
warning = self.page.locator(".py-warning")
|
||||
inner_text = warning.inner_text()
|
||||
inner_text = warning.inner_html()
|
||||
assert "The setting autoclose_loader is deprecated" in inner_text
|
||||
|
||||
div = self.page.locator("py-splashscreen > div")
|
||||
|
||||
Reference in New Issue
Block a user