基本使用方法
共有3步骤。
编写HTML文件
新建一个名为hello-from-pyscript.html文件,内容如下:
<!DOCTYPE html>
<html>
<head>
<title>PyScript Demo</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://pyscript.net/releases/2024.10.2/core.css">
<script type="module" src="https://pyscript.net/releases/2024.10.2/core.js"></script>
<script type="py" src="./main.py" config="./pyscript.json"></script>
<style>
body {
color: #ACB7C4;
background: #2B2B2B;
margin: 1em;
}
#main {
display: none;
}
h1 {
color: cyan;
}
#loading {
outline: none;
border: none;
background: transparent;
}
#loading h1 {
color: lightgreen;
}
table {
margin-top: 1em;
border: 1px solid gray;
}
button {
padding: 0.5em;
}
</style>
<script type="module">
const loading = document.getElementById("loading");
const mainDiv = document.getElementById("main");
window.addEventListener('py:ready', () => {
loading.close();
mainDiv.style.display = "block";
});
loading.showModal();
</script>
</head>
<body>
<dialog id="loading">
<h1>Loading...</h1>
</dialog>
<div id="main">
<h1>Web Python, Powered by PyScript</h1>
<button py-click="doIt">Click on Me</button>
<div id="out"></div>
</div>
</body>
</html>
PyScript所需文件共有2件,分别为core.css及core.js。
在上面两个文件加载完毕后,代码:
<script type="py" src="./main.py" config="./pyscript.json"></script>
做了两件事情。一是通过读取pyscript.json文件内容来配置工程。例如,若要使用第三方的库,则需在此文件中指定。二是指定要Python的源文件为main.py。type="py"
确保PyScript来这里提取所需要的信息。
上面这行代码外置了Python源文件,也可以改为内置的脚本:
<script type="py">
import numpy as np
from pyscript import display, HTML
...
</script>
下面这两行代码,以PyScript的方式来绑定具体的Web事件:
window.addEventListener('py:ready', () => {
...
});
<button py-click="doIt">Click on Me</button>
编写配置文件
新建一个名为pyscript.json文件,内容如下:
{
"name": "Hello World",
"description": "A Demo app of PyScript",
"packages": ["numpy"]
}
这里我们需要使用第三方类库numpy,因此通过"packages": ["numpy"]
进行配置。
编写Python源代码
新建一个名为main.py文件,内容如下:
import numpy as np
from pyscript import display, HTML
def doIt(event):
narr = np.arange(10)
tableStartStr = """
<table>
<tr>
"""
tableEndStr = """
</tr>
</table>
"""
for n in narr:
tableStartStr += f'<td>{n}</td>'
display(HTML(tableStartStr + tableEndStr), target="out", append=False)
上面使用numpy生成一个列表,并显示在网页上。
display函数的append参数若为True,则每次都会添加新的DOM;值为False时,则先删除原来的DOM,再重新添加。
运行网页。
PyScript的设置还是比较简单的,上面较长的代码用于设置CSS样式。
尽管上面的代码只加载了两个必须的文件,但PyScript实际上还加载了其他的辅助文件,因此这一过程有点嫌久(大约2秒种),故上面的代码设置了Loading...
的提示页面。