One skill a day: Throw away JavaScript and build a website with HTML and Python

WBOY
Release: 2023-04-11 23:52:08
forward
1195 people have browsed it

有时候,我们的电脑上没有安装Python,但你需要验证一段Python代码的运行效果。

又有时候,你想做一个网页,但是你只会HTML和Python。那么如果要做一个带有一些复杂逻辑的网页,只能去学JavaScript吗?

其实未必。如果你不考虑网页美观的话,你可以用HTML + Python实现一个简单的网页。

今天我们要介绍的东西,叫做PyScript,使用它,不需要安装任何软件。只要有一个记事本,就能写一段HTML+Python的代码。写完以后,双击这个HTML文件,用浏览器打开,就能直接看到Python代码的运行结果。

假设我现在要写一段代码,使用高效的算法计算斐波那契数列前10项的值。现在我已经把代码写好了,想验证一下它是否正确:

def fib(n):
if n in [1, 2]:
return 1
a = 1
b = 1
for _ in range(2, n):
a, b = b, a + b
return b
Copy after login

我的电脑上没有Python,我也不知道任何在线的Python解释器。怎么办呢?这个时候,你只需要在这个Python代码的前后再添加一些HTML代码,把它保存成一个.html文件就可以了:

<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<py-script>
def fib(n):
if n in [1, 2]:
return 1
a = 1
b = 1
for _ in range(2, n):
a, b = b, a + b
return b

for i in range(1, 11):
print(f'第{i}项的结果是:{fib(i)}')
</py-script>
</body>
</html>
Copy after login

保存以后,双击这个HTML文件,用浏览器打开,就可以看到运行结果了,如下图所示:

One skill a day: Throw away JavaScript and build a website with HTML and Python

到目前为止,似乎跟那些在线的Python运行环境没什么区别。但PyScript更厉害的是,它自带了一些常见的第三方库,例如numpy或者Matplot,甚至它还可以手动安装第三方库。

对于它自带的numpy和matplotlib,可以直接使用标签声明:

<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<py-env>
- numpy
- matplotlib
</py-env>
</head>

<body>
<h1>Let's plot random numbers</h1>

<py-script output="plot">
import matplotlib.pyplot as plt
import numpy as np

x = np.random.randn(1000)
y = np.random.randn(1000)

fig, ax = plt.subplots()
ax.scatter(x, y)
fig
</py-script>
</body>
</html>
Copy after login

运行效果如下图所示:

One skill a day: Throw away JavaScript and build a website with HTML and Python

如果你想安装第三方库,只需要去下载这个库对应的.whl文件,把它跟HTML文件放到一起,然后在中使用相对路径导入就可以了。但经过我的测试,导入的requests工作起来有点问题。因此就不多介绍了。看看官方是否会修复这个bug吧。

PyScript的Github[1]上,给了不少Demo,甚至可以用它来做超级马里奥的网页游戏。大家有兴趣可以看看。

总结

目前仅仅从运行Python代码这个小功能上,PyScript做的比Jupyter还是差远了。但是PyScript可以编辑修改HTML元素,这样它就可以在一定程度上替代JavaScript,从而配合HTML实现一些功能复杂的网页。

参考资料

[1]Github: https://github.com/pyscript/pyscript

The above is the detailed content of One skill a day: Throw away JavaScript and build a website with HTML and Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:51cto.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!