Brython Chinese Documents

Introduction 1. brython

References W3C Document Object Model specification:
What is the Document Object Model?
Document Object Model is a platform- and language-neutral interface that allows content, structure and style of programs and scripts to dynamically access and update the document.

Brython goal is to replace the use Javascript Python, a scripting language Web browser.

A simple example:

<html>
<head>
	<script src="/brython.js"></script>
</head>
<body onload="brython()">

<script type="text/python">
from browser import document, alert

# 给按钮绑定事件‘click’到方法‘echo’上
def echo(ev):
    alert(document["zone"].value)

document["mybutton"].bind("click", echo)
</script>

<input id="zone">
<button id="mybutton">click !</button>
</body>
</html>

To handle Python script must contain brython.jsand brython()run the function (using the tag when the page is loaded onloadproperty <BODY>). During the development phase, the parameters can be passed to brython()the function: 1 will display an error message to the Web browser console 2 may be displayed together with the display error Javascriptcodes.

If large Python programs, another option is to write it in a separate file and use the src attribute of the script tag to load it:

<html>
	<head>
		<script src =“/ brython.js”> </ script>
	</head>

<body onload =“brython()”>
<script type =“text / python”src =“test.py”> </ script>
<input id =“zone”autocomplete =“off”>
<button id =“mybutton”> click!</ button>
</body>

</html>

Please note that in this case, Python script by Ajaxcalling load: it must be HTMLin the same domain page.
In the two previous code example, when we click the button, onclickthe event will call and run echo()functions defined in the Python script. This function by which id(region) Gets INPUTthe value of the element. This is achieved by the following syntax document["zone"]:documentdefined in the module browser, it is a subject of the document currently being displayed in the browser. It behaves like a dictionary, which is a key DOMelement ID. Thus, in our example, document["zone"]is mapped to a INPUTtarget element; the value of the property saved, it is interesting that the value of the object.
In Brython, the output can be accomplished by various ways, including the use of the function alert()(also defined browser), the pop-up display function, a text as a parameter.

2. Install

2.1 Installation brython

  • If your computer has CPython and pip, installation brython by the following method

     # 先安装brython
     pip install brython
     
     # 然后在一个空目录下运行
     python -m brython --install
    
  • If you can not use this method, go to the published page on Github, select the latest version, download and unzip Brython-xyzzip.

In both cases, this directory contains the following files:
brython.js : included in the HTMLpages of the Brythonengine
brython_stdlib.js : for Brythonall supported Python standard library modules and packages part of the group
demo.html : a page It contains how to use Brythonclient-side development example
brython.js include frequently used modules: browser, browser.html, javascript.

If your application uses the standard distribution module, you apart from brython.jsoutside also need to include brython_stdlib.js:

    <script type =“text / javascript”src =“brython.js”> </ script> 
    <script type =“text / javascript”src =“brython_stdlib.js”> </ script>

2.2 update

Released a new version Brython, the update is done by commonly used commands:

pip install brython --upgrade

In the application directory, you can update the following ways Brythonfiles ( brython.jsand brython_stdlib.js):

python -m brython --update

2.3 installation package CPython
CPython pip installation package may be installed by the command on Brython -add package applications.
E.g:

pip install attrs 
python -m brython --add_package attrs

All files in the package must of course be used by Brython; for example, this document does not include the C language.

2.4 Other commands

-- modules

Create a distribution-specific applications, to replace brython_stdlib.js smaller files. See the import section.

-- make_dist

CPython generate a package for PyPI release, install a Brython application. Refer to deploy an application Brython

Network Server 2.5
can be opened in the browser HTMLfiles, it is recommended to start the Web server in the application directory.
The most direct is to CPythonuse the module in the standard distribution http.server:

python -m http.server

The default port is 8000. To choose another port:

python -m http.server 8001

Then, you can enter in the browser address bar http:// localhost:8001 / demo.htmlto access these pages.

3. related issues

4. Keywords and built-in functions

Brython is based Python3 achieve.
This implementation takes into account the browser's limitations, particularly related to the file system limitations. It is impossible to write, and read only file a request with Ajax accessible folder.

4.1 keywords and built-in functions
Brython support Python 3most of the functions and keywords:
Keywords: and, as, assert, async, await, break, class, continue, def, del, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield
built-in functions and classes: abs, all, any, ascii, bin, bool, bytes, callable, chr, classmethod, delattr, dict, dir, divmod, enumerate, eval, exec, filter, float, frozenset, getattr, globals, hasattr, hash, hex, id, input, int, isinstance, iter, len, list, locals, map, max, memoryview, min, next, object, open, ord, pow, print, property, range, repr, reverse, round, set,setattr,slice,sorted,str, sum, super, tuple, type, vars, zip, import

The following are some of the features and limitations imposed by browsers and Javascript:

  • Before turning to the next instruction, Javascript function to perform a given time can not stop or wait for the event to occur. for this reason:

    • the time.sleep () can not be used: function module browser.timer, such set_timeout () or set_interval () must be used
    • Built-in input () function from the function simulation Javascript prompt ()
  • For the same reason, and because the browser has its own implicit event loop, CPython asyncio module is not available. Browser.aio Brython specific to a module for asynchronous programming.

  • Built-in open () function to open the url of the file as a parameter. Because it is using Ajax calls to read, so it must be in the same domain as the script. Object returned open () has a generally read and access methods: read, readlines, seek, tell, close. Text only mode: Ajax call blocking, in this mode can not be set responseType property

  • By default, print () output to the Web browser console, an error message is true. and may be used sys.stderr sys.stdout write () method to assign it to the object, which, for example, to allow output to a window or text area.

  • Open the Print dialog box (printer), call window.print (window defined in the module browser).

  • sys.stdin not implemented at this time, but there is an input () built-in function to open the blocked input dialog box (prompt).

  • Object life cycle management by the garbage collector Javascript, Brython CPython did not manage reference counting. Thus, del () when no longer referenced class instance, the method is not called.

  • Use Javascript JSON parser; a real number (e.g., 1.0) Thus, the integer is converted to an integer json.dumps ().

4.2 Built-value name
built-in variables __name__ to the value of id attribute of the script. E.g:

<script type="text/python" id="myscript">
assert __name__ == 'myscript'
</script>

If the two scripts have the same idexception is thrown.

For there is no explicit idset of scripts:

  • If the script is not idset to __main__, the first "unnamed" script to __name__ set to " main ." Therefore, if the page is only one script, it will be able to run the usual tests:

    <script type="text/python">
    if __name__=='__main__':
        print('hello !')
    </script>
    
  • For other scripts unnamed, __name__it will be set at __main__the beginning of the random string.

5. Import

5.1 Import
and Python as standard, or you can install the module in the application package, is to put them in the root directory, or on file with the __init__.pydirectory.
Please note that the module must be encoded in utf-8; encoding declaration at the top of the script will be ignored.
For example, an application may consist of the following files and directories:

.bundle-include
app.html
brython.js
brython_modules.js
brython_stdlib.js
index.html
users.py
utils.py
+ app
    __init__.py
    records.py
    tables.py

app.html in Python scripts can be run import

import users
import app.records

If the standard distributions is included in the page

<script type =“text / javascript”src =“brython_stdlib.js”> </ script>

The script can also be run

import datetime
import re

To import the module or pack, Brython CPython using the same mechanism: To resolve the " import X", the program looks for files in several places:

  • Standard distribution module X.
  • The root directory of the file X.py.
  • X Files directory__init__.py

Because the browser can not directly access the file system, it is necessary to find the file by Ajax calls, if there is no file on the specified URL, it will return an error message.

5.2 optimize
this process has two major drawbacks:

  • Relatively large brython_stdlib.js(more than 3 Mb)
  • Ajax call takes time

To optimize introduced, if installed Brython, the pip can generate a file brython_modules.jsthat contains only the modules used by the application.
To do this, open a console window, navigate to the application directory and execute

python -m brython --modules

Please note that all scripts parse the program directory and its subdirectories, modules and HTMLpages of Brythoncode. Use the CPythonversion must comply with this BrythonCode: For example, if Brythonthere are f string code, you need to CPython 3.6+, otherwise a syntax error will occur.
You can then replace all occurrences

<script type =“text / javascript”src =“brython_stdlib.js”> </ script>

by

<script type =“text / javascript”src =“brython_modules.js”> </ script>

6. The browser interface-related

6.1 DOM api Introduction

For the interface with the browser, Brython in line with the Document Object Model interface, which is widely documented on Web:

  • Reference W3C
  • Wikipedia Page
  • Mozilla website

The interface is independent of language. Use Brython, DOM APIall operations described in the two objects are defined in dependent browser module: documentandwindow

documentImplement DocumentDOM APIthe interface defined. For example, it supports the following methods:

document.getElementById(elt_id)

Returns id of the DOM element reference elt_id

document.createElement(tagName)

TagName returns a new element types; for example, to create a hypertext link:

link = document.createElement('A')
document.appendChild(elt)

The elements eltadded to the document in
addition to this standard interface, Brython also proposed an alternative interface for Brython developers more familiar. It is described in the following pages.

6.2 Create documents

BrythonFor writing Web applications, so the user can interact with HTMLthe page

A page from the elements (text, images, sound ...) composition, may be included in the page in two different ways:

  • For example, the label written in HTMLthe code
<html>
<body>
<b>Brython</b> is an implementation of <a href="http://www.python.org">Python</a>
for web browsers
</body>
</html>
  • Built-in module or browser.htmlto write Pythonthe code
<html>
<body>
<script type="text/python">
from browser import document
from browser.html import A,B

document <= B("Brython")+"is an implementation of "
document <= A("Python",href="http://www.python.org")+" for web browsers"
</script>
</body>
</html>

Guess you like

Origin blog.csdn.net/sinat_31580685/article/details/93011227