根據(jù)官方介紹,這個(gè)名為PyScript的框架,其核心目標(biāo)是為開(kāi)發(fā)者提供在標(biāo)準(zhǔn)HTML中嵌入Python代碼的能力,使用 Python調(diào)用JavaScript函數(shù)庫(kù),并以此實(shí)現(xiàn)利用Python創(chuàng)建Web應(yīng)用的功能。
看到介紹里提到了調(diào)用JavaScript函數(shù)庫(kù)的能力,看來(lái)跟JSP或者模版引擎還是有區(qū)別的。
#PyScript 快速體驗(yàn)
官方給了一個(gè)例子,可以幫助我們觀的感受這個(gè)開(kāi)發(fā)框架的能力,不妨跟著DD看看,它能做啥吧!
第一個(gè)案例,hello world
代碼很簡(jiǎn)單,就下面這幾行。你只需要?jiǎng)?chuàng)建一個(gè)html文件,然后復(fù)制進(jìn)去就可以了。
<html>
<head>
<link rel="stylesheet" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<py-script>
print('Hello, World!')
</py-script>
</body>
</html>
保存好之后,在瀏覽器里打開(kāi)就能看到這樣的頁(yè)面了:
回頭再看看這個(gè)html里的內(nèi)容,三個(gè)核心內(nèi)容:
- 引入pyscript的樣式文件:
<link rel="stylesheet" />
- 引入pyscript的腳本文件:
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<py-script>
標(biāo)簽中寫(xiě)具體的python代碼來(lái)輸出Hello World
本文的兩個(gè)案例代碼我打包放在公眾號(hào)了,需要的朋友可以關(guān)注公眾號(hào)“程序猿DD”,回復(fù):pyscript 獲取。
第二個(gè)案例,數(shù)據(jù)定義 + 數(shù)據(jù)展示
先創(chuàng)建一個(gè)data.py
文件,然后加入前面的代碼。功能很簡(jiǎn)單,就是隨機(jī)生成(x,y)的坐標(biāo)
import numpy as np
def make_x_and_y(n):
x = np.random.randn(n)
y = np.random.randn(n)
return x, y
再創(chuàng)建一個(gè)html文件,加入下面的代碼
<html>
<head>
<link rel="stylesheet" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<py-env>
- numpy
- matplotlib
- paths:
- /data.py
</py-env>
</head>
<body>
<h1>Let's plot random numbers</h1>
<div id="plot"></div>
<py-script output="plot">
import matplotlib.pyplot as plt
from data import make_x_and_y
x, y = make_x_and_y(n=1000)
fig, ax = plt.subplots()
ax.scatter(x, y)
fig
</py-script>
</body>
</html>
這里就稍微復(fù)雜一些了,除了hello world中的幾個(gè)要點(diǎn)外,這里還有這幾個(gè)要關(guān)注的地方:
<py-env>
標(biāo)簽:這里聲明要引入的包和要引入的文件(上面創(chuàng)建的data.py
)<py-script output="plot">
:這里定義了要在<div id="plot"></div>
中輸出的內(nèi)容,可以看到這里的邏輯都是用python寫(xiě)的
這個(gè)頁(yè)面的執(zhí)行效果是這樣的: