+
95
-

回答

Brython可以替代javascript在使用python来编写浏览器脚本。

brpython的目标是用Python取代Javascript,作为Web浏览器的脚本语言。

我们先看一个示例代码

<!DOCTYPE html>

<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello World</title>
<script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/brython.min.js"></script>
<script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/brython_stdlib.js"></script>
</head>
<bodyBfwOnload="brython()">
<script type="text/python">
from browser import document
document <= "Hello World!"
</script>
</body>
</html>

你会惊奇的发现竟然输入了helloworld


再来个弹窗

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello World</title>
<script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/brython.min.js"></script>
<script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/brython_stdlib.js"></script>
</head>
<bodyBfwOnload="brython()">
<script type="text/python">
import browser
browser.alert("Hello Real Python!")
</script>
</body>
</html>

其他场景用法:

建立 a link

link1 = A('Brython', href='http://www.brython.info')

link2 = A(B('Python'), href='http://www.python.org')

建立 a 并 附加属性

link = A()

link <= B('connexion')

link.href = 'http://example.com'

AJAX

req = ajax()
req.on_complete = on_complete
req.set_timeout(timeout, err_msg)
req.open('POST', url, True)
req.set_header('content-type', 'application/x-www-form-urlencoded')
req.send(data)

Local storage

local_storage['foo'] = 'bar'
log(local_storage['foo'])
del local_storage['foo']
log(local_storage['foo']) # prints None

Brython 相关 Library (库)

库的套件可见: Brython - Compiling and running

这边有很多必须的 Library, 在这边列一些应用类的.

py2js.js : does the conversion between the tokens and the Javascript code

py_dom.js : interaction with the HTML document (DOM)

py_ajax.js : Ajax implementation

py_local_storage.js : implementation of the HTML5 local storage

py_svg.py : SVG support (vector graphics)

网友回复

我知道答案,我要回答