pyscript (官网) 支持在 html 中使用纯 python 语法的脚本标签. 形如下面的示例:
<html>
<py-script>
print("now you can run python in your html!")
</py-script>
</html>
部分了解过 brython 的人可能对此感到熟悉, 但二者也有显著的不同:
pyscript 是以 “pyscript.js” 和 “pyscript.css” 的形式提供. 因此我们有两种方式引入:
在线引用
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
下载后本地引用
下载 官网提供的压缩包 到本地 (zip 文件, 体积约 4.5mb, 解压后约 5.5mb).
然后在 html 中引用:
<link rel="stylesheet" href="~/pyscript.css" />
<script defer src="~/pyscript.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>PyScript Hello World</title>
<link rel="icon" type="image/png" href="favicon.png" />
<link rel="stylesheet" href="~/pyscript.css" />
<script defer src="~/pyscript.js"></script>
</head>
<body>
Hello world! <br>
This is the current date and time, as computed by Python:
<py-script>
from datetime import datetime
now = datetime.now()
now.strftime("%Y-%d-%m %H:%M:%S")
</py-script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Todo App</title>
<link rel="icon" type="image/png" href="favicon.png" />
<link rel="stylesheet" href="~/pyscript.css" />
<script defer src="~/pyscript.js"></script>
<!-- 注意, 在这里我们通过 py-env 标签来引入第三方库和模块. -->
<py-env>
- paths:
- /utils.py
</py-env>
</head>
<body>
<!-- py-script 标签也是可以通过 src 属性引入 py 文件的. -->
<py-script src="/todo.py"> </py-script>
</body>
</html>