If you’re a web developer who prefers writing Python over JavaScript, then Brython, a Python implementation that runs in the browser, may be an appealing option
JavaScript là ngôn ngữ thực tế của phát triển web front-end. Sophisticated JavaScript engines are an inherent part of all modern Internet browsers and naturally drive developers to code front-end web applications in JavaScript. Brython offers the best of both worlds by making Python a first-class citizen language in the browser and by having access to all the existing JavaScript libraries and APIs available in the browser
In this tutorial, you’ll learn how to
- Install Brython in your local environment
- Use Python in a browser
- Write Python code that interacts with JavaScript
- Deploy Python with your web application
- Create browser extensions with Python
- Compare Brython with other Python implementations for web applications
As an intermediate Python developer familiar with web development, you’ll get the most out of this tutorial if you also have some knowledge of HTML and JavaScript. For a JavaScript refresher, check out Python vs JavaScript for Pythonistas
You can download the source material for the examples in this tutorial by clicking the link below
Get the Source Code. Click here to get the source code you’ll use to learn about using Brython to run Python in the browser in this tutorial
Running Python in the Browser. The Benefits
Although JavaScript is the ubiquitous language of front-end web development, the following points may apply to you
- You may not like writing code in JavaScript
- You may want to leverage your Python skills
- You may not want to spend the time to learn JavaScript to explore browser technologies
- You may not like being forced to learn and use JavaScript to implement a web application
Whatever the reason, many developers would prefer a Python-based alternative to JavaScript for leveraging the power of the browser
There are several benefits of running Python in the browser. It allows you to
- Execute the same Python code in the server and the browser
- Work with various using Python
- Manipulate the Document Object Model [DOM] with Python
- Use Python to interact with existing JavaScript libraries like Vue. js and jQuery
- Dạy ngôn ngữ Python cho sinh viên Python với trình soạn thảo Brython
- Keep the sense of fun while programming in Python
One side effect of using Python in the browser is a loss of performance compared to the same code in JavaScript. However, this drawback doesn’t outweigh any of the benefits outlined above
Remove adsTriển khai phát triển web đẳng cấu
JavaScript đẳng cấu hoặc JavaScript phổ quát, nhấn mạnh rằng các ứng dụng JavaScript nên chạy trên cả máy khách và máy chủ. Điều này giả định rằng phần cuối dựa trên JavaScript, cụ thể là máy chủ Node. Các nhà phát triển Python sử dụng Flask hoặc Django cũng có thể áp dụng các nguyên tắc đẳng cấu cho Python, miễn là họ có thể chạy Python trong trình duyệt
Brython cho phép bạn xây dựng giao diện người dùng bằng Python và chia sẻ các mô-đun giữa máy khách và máy chủ. Ví dụ: bạn có thể chia sẻ các chức năng xác thực, chẳng hạn như mã sau chuẩn hóa và xác thực số điện thoại của Hoa Kỳ
1import re
2
3def normalize_us_phone[phone: str] -> str:
4 """Extract numbers and digits from a given phone number"""
5 return re.sub[r"[^\da-zA-z]", "", phone]
6
7def is_valid_us_phone[phone: str] -> bool:
8 """Validate 10-digit phone number"""
9 normalized_number = normalize_us_phone[phone]
10 return re.match[r"^\d{10}$", normalized_number] is not None
import antigravity
2 loại bỏ mọi ký tự không phải chữ và số, trong khi import antigravity
3 trả về import antigravity
4 nếu chuỗi đầu vào chứa chính xác mười chữ số và không có ký tự chữ cái. The same code can be shared between processes running on a Python server and a client built with BrythonAccessing Web APIs
Internet browsers expose standardized web APIs to JavaScript. These standards are part of the HTML Living Standard. Some web API examples include
- Web Storage
- Web Crypto
- Web Workers
- Lịch sử
- URL
Brython allows you to both use the web APIs and interact with JavaScript. You’ll work with some of the web APIs in
Prototyping and JavaScript Libraries
Python is often used to prototype snippets of code, language constructs, or bigger ideas. With Brython, this common coding practice becomes available in your browser. For example, you can use the Brython console or the interactive editor to experiment with a snippet of code
Open the online editor and type the following code
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
Here’s how this code works
- Line 1 imports the
5 moduleimport antigravity
- Line 3 defines
6, the callback function that’s invoked after getting the response fromimport antigravity
7import antigravity
- Line 6 calls
7 to retrieve the translation of “hello” in French using the HelloSalut API. Note thatimport antigravity
9 can beimport antigravity
4 orimport antigravity
1 when you execute this code in the Brython editor. It needs to be1 2 3 4 6 7 8 9 10 import browser 11 browser.alert["Hello Real Python!"] 12 13 14
4 if you execute the same code in the Brython consoleimport antigravity
Click Run above the output pane to see the following result
{"code":"fr","hello":"Salut"}
Try modifying the language from
1
2
3
4
6
7
8
9
10 import browser
11 browser.alert["Hello Real Python!"]
12
13
14
3 to 1
2
3
4
6
7
8
9
10 import browser
11 browser.alert["Hello Real Python!"]
12
13
14
4 and observe the result. The language codes supported by this API are listed in the HelloSalut documentationNote. HelloSalut is one of the public APIs available on the Internet and listed in the Public APIs GitHub project
You can modify the code snippet in the online editor to consume a different public API. For example, try to fetch a from the Public APIs project
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
Copy the code above into the online Brython editor and click Run to display the result. Here’s an example in JSON format
{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
Because the endpoint fetches a random project, you’ll probably get a different result. For more information about the JSON format, check out Working With JSON Data in Python
You can use prototyping to try out regular Python code as you would in the Python interpreter. Because you’re in the context of a browser, Brython also provides ways to
- Learn how to use the web APIs
- Interact with the Document Object Model [DOM]
- Use existing JavaScript libraries like jQuery, D3, and Bokeh as well as JavaScript UI frameworks like Vue. js
As a shortcut, you can take advantage of most of the features described above by opening the console or editor available on the Brython website. This doesn’t require you to install or run anything on your local computer. Instead, it gives you an online playground to interact with both Python and web technologies
Remove adsTeaching Python to Students
Brython is both a Python compiler and an interpreter written in JavaScript. As a result, you can compile and run Python code in the browser. A good example of this feature is demonstrated by the online editor available on the Brython website
With the online editor, Python is running in the browser. There’s no need to install Python on a machine, and there’s no need to send code to the server to be executed. The feedback is immediate for the user, and this approach doesn’t expose the back end to malicious scripts. Students can experiment with Python on any device with a working browser, such as phones or Chromebooks, even with a spotty internet connection
Taking Performance Into Account
The Brython site notes that the implementation’s execution speed is comparable to CPython. But Brython is executed in the browser, and the reference in this environment is JavaScript baked into the browser engine. As a result, expect Brython to be slower than hand-written, well-tuned JavaScript
Brython compiles Python code into JavaScript and then executes the generated code. These steps have an impact on overall performance, and Brython may not always meet your performance requirements. In some cases, you may need to delegate some code execution to JavaScript or even WebAssembly. You’ll see how to build WebAssembly and how to use the resulting code in Python in the section on
However, don’t let perceived performance detract you from using Brython. For example, importing Python modules may result in downloading the corresponding module from the server. To illustrate this situation, open the Brython console and execute the following code
>>>
>>> import uuid
The delay until the prompt is displayed [390 ms on a test machine] is noticeable. This is due to Brython having to download
1
2
3
4
6
7
8
9
10 import browser
11 browser.alert["Hello Real Python!"]
12
13
14
5 and its dependencies and then compile the downloaded resources. However, from that point on, there’s no delay while executing functions available in 1
2
3
4
6
7
8
9
10 import browser
11 browser.alert["Hello Real Python!"]
12
13
14
5. For example, you can generate a , UUID version 4, with the following code>>>
>>> uuid.uuid4[]
UUID['291930f9-0c79-4c24-85fd-f76f2ada0b2a']
Calling
1
2
3
4
6
7
8
9
10 import browser
11 browser.alert["Hello Real Python!"]
12
13
14
7 generates a object, whose string representation is printed in the console. Calling 1
2
3
4
6
7
8
9
10 import browser
11 browser.alert["Hello Real Python!"]
12
13
14
7 returns immediately and is much quicker than the initial import of the 1
2
3
4
6
7
8
9
10 import browser
11 browser.alert["Hello Real Python!"]
12
13
14
5 moduleHaving Fun
If you’re reading this tutorial, then you’re probably interested in writing Python code in the browser. Seeing Python code executed in the browser is exciting for most Pythonistas and awakes a sense of fun and endless possibility
The author of Brython, Pierre Quentel, and the contributors to the project also kept the fun of Python in mind while undertaking the huge task of making this language compatible with the web browser
To prove it, point your browser to the Brython interactive console, and at the Python prompt, type the following
import this
Similar to the experience of Python on your local machine, Brython compiles and executes the instructions on the fly and prints The Zen of Python. It takes place in the browser and the Python code execution does not require any interaction with a back-end server
You can also try another classic Python Easter egg in the same browser environment with the following code
import antigravity
Brython embraces the same bits of humor that you’ll find in the Python reference implementation
Now that you’re familiar with the basics of working with Brython, you’ll explore more advanced features in the following sections
Remove adsInstalling Brython
Experimenting with Brython’s online console is a good start, but it won’t allow you to deploy your Python code. There are several different options for installing Brython in a local environment
Instructions for each of these methods are outlined below, but feel free to skip directly to your preferred approach if you’ve already made a decision
CDN Installation
Mạng phân phối nội dung [CDN] là mạng máy chủ cho phép cải thiện hiệu suất và tốc độ tải xuống cho nội dung trực tuyến. You can install Brython libraries from a few different CDNs
- CDNJS
- jsDelivr
- CDNPKG
You may choose this installation if you want to deploy a static website and add some dynamic behaviors to your pages with minimum overhead. You can think of this option as a substitute for jQuery, except using Python rather than JavaScript
To illustrate the use of Brython with a CDN, you’ll use CDNJS. Tạo một tệp có mã HTML sau
1
2
3
4
6
7
8
9
10 import browser
11 browser.alert["Hello Real Python!"]
12
13
14
Dưới đây là các yếu tố chính của trang HTML này
Dòng 5 tải
01 từ CDNJS1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
Dòng 8 thực thi
02 khi tài liệu tải xong.1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
02 reads the Python code in the current scope and compiles it to JavaScript. See the section for more details1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
Line 9 sets the type of the script to
04. This indicates to Brython which code needs to be compiled and executed1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
Line 10 imports
05, a Brython module that exposes objects and functions allowing interaction with the browser1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
Line 11 calls
06, which displays a message box with the text1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
071from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
Save the file as
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
08, then double-click the file to open it with your default Internet browser. The browser displays a message box with 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
07 Click OK to close the message boxTo reduce the size of the downloaded file, especially in production, consider using the minimized version of
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
01 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
0The minimized version will reduce the download time and perceived latency from the user’s standpoint. In , you’ll learn how Brython is loaded by the browser and how the above Python code is executed
GitHub Installation
The GitHub installation is very similar to the CDN installation, but it allows you to implement Brython applications with the latest development version. You can copy the previous example and modify the URL in the
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
11 element to get the following 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
08 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
1After saving this file in a local directory, double-click
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
08 to render in the browser the same page you obtained with the CDN installRemove adsCài đặt PyPI
So far, you haven’t needed to install anything in your local environment. Instead, you’ve indicated in the HTML file where the browser can find the Brython package. When the browser opens the page, it downloads the Brython JavaScript file from the appropriate environment, from either a CDN or GitHub
Brython is also available for local installation on PyPI. The PyPI installation is for you if
- You need more control and customization of the Brython environment beyond what’s available when pointing to a CDN file
- Your background is in Python and you’re familiar with
141from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
- You want a local installation to minimize network latency during development
- You want to manage your project and deliverables in a more granular fashion
Installing Brython from PyPI installs
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
15, a command-line tool that you can use to automate functions like generating a project template or packaging and bundling modules to simplify deployment of a Brython projectFor more details, you can consult the local installation documentation to see the capabilities of
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
16 that are available in your environment after installation. 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
16 is available only with this type of installation. It isn’t available if you install from a or with . You’ll see 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
16 in action later in the tutorialBefore installing Brython, you want to create a Python virtual environment for this project
On Linux or macOS, execute the following commands
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
2On Windows, you can proceed as follows
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
3You’ve just created a dedicated Python environment for your project and updated
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
14 with the latest versionIn the next steps, you’ll install Brython and create a default project. The commands are the same on Linux, macOS, and Windows
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
4You’ve installed Brython from PyPI, created an empty folder named
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
20, and generated the default project skeleton by executing the 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
16 copied in your virtual environment during the installationIn the
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
20 folder, 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
23 created a project template and generated the following filesFileDescription
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
24Documentation on how to run a Python HTTP server and open 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
25 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
01Core Brython engine [compiler, runtime, and browser interface] 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
27Brython standard library 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
25Source code of the Brython demo HTML page 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
08Basic example that you can use as a starting page for a project 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
30Unicode Character Database [UCD] used by 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
31To test this newly created web project, you can start a local Python web server with the following commands
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
5When you execute
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
32, Python starts a web server on port 8000. The expected default page is 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
08. Point your internet browser to 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
34 to display a page with the text 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
35For a more complete example, you can change the URL in the browser’s address bar to
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
36. You should see a page similar to the Brython demo pageWith this approach, the Brython JavaScript files are loaded directly from your local environment. Notice the
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
37 attribute in the 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
11 element of 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
08 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
6The HTML above is indented to enhance readability in this tutorial. The command
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
40 does not indent the initial HTML template that it generatesThe HTML file introduces a few new Brython features
Line 6 loads
27, the Python standard library compiled to JavaScript1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
Line 8 invokes
02 with the argument1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
43 to print error messages to the browser console1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
Line 10 imports the
44 module from1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
05. Functions to access the DOM are available in1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
441from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
Line 11 shows a new symbol [
47] added to Python as syntactic sugar. In this example,1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
48 is a substitute for1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
49. For details about these DOM functions, check out1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
501from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
The operator
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
47 is used to add a child node to an element of the DOM. You’ll see in more details on using Brython-specific operators in Remove adsnpm Installation
If you’re well versed in the JavaScript ecosystem, then the npm installation might appeal to you. Node. js and npm are required before performing this install
Installing with npm will make the JavaScript Brython modules available in your project like any other JavaScript modules. You’ll then be able to take advantage of your favorite JavaScript tooling to test, package, and deploy the Brython interpreter and libraries. This installation is ideal if you already have existing JavaScript libraries installed with npm
Note. If you don’t have Node. js and npm installed on your system, then consider reading the rest of this section for information only, as you can safely skip the installation itself. The remainder of the tutorial doesn’t depend on the npm installation method for any of the examples
Assuming that you have npm installed on your system, create a default
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
52 file by invoking 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
53 in an empty directory 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
7To integrate Brython into your project, execute the following command
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
8You can ignore the warnings and note that Brython was added to your project. To confirm, open
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
52 and make sure you have a 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
55 property pointing to an object containing a 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
56 entry 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
9As for the previous examples, you can create the following
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
08 and open it with your browser. A web server isn’t needed for this example because the browser is able to load the JavaScript file 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
58 locally{"code":"fr","hello":"Salut"}
0The browser renders
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
08 and loads 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
01 from the 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
61 URL in 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
08. In this example, you’ve seen a different way to install Brython that takes advantage of the JavaScript ecosystem. For the remainder of the tutorial, you’ll write code that relies on the CDN installation or the PyPI installationRecap of Brython Installation Options
Brython có một chân trong thế giới Python và một chân khác trong JavaScript. The different installation options illustrate this cross-technology situation. Pick the installation that feels the most compelling to you based on your background
The following table provides you with some guidance
Type of InstallationContextCDNYou want to deploy a static website and add some dynamic behaviors to your pages with minimum overhead. You can think about this option as a substitute for jQuery, except using Python rather than JavaScript. GitHub Điều này tương tự như cài đặt CDN, nhưng bạn muốn thử nghiệm với phiên bản mới nhất của Brython. PyPIYour background is in Python. You’re familiar with
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
14 and how to create Python virtual environments. Dự án của bạn có thể yêu cầu một số tùy chỉnh mà bạn muốn duy trì trong môi trường cục bộ hoặc trong kho lưu trữ mã nguồn của bạn. Bạn muốn có nhiều quyền kiểm soát hơn đối với gói mà bạn sẽ phân phối. Bạn muốn triển khai trong môi trường khép kín không cần truy cập Internet. npmNền của bạn bằng JavaScript. Bạn đã quen thuộc với các công cụ JavaScript, cụ thể là Node. js và npm. Dự án của bạn có thể yêu cầu một số tùy chỉnh mà bạn muốn duy trì trong môi trường cục bộ hoặc trong kho lưu trữ mã nguồn của bạn. Bạn muốn có nhiều quyền kiểm soát hơn đối với các gói bạn sẽ phân phối. Bạn muốn triển khai trong môi trường khép kín không cần truy cập InternetBảng này tóm tắt các tùy chọn cài đặt khác nhau có sẵn cho bạn. Trong phần tiếp theo, bạn sẽ tìm hiểu thêm về cách hoạt động của Brython
Hiểu cách hoạt động của Brython
Chuyến tham quan của bạn về các cách khác nhau để cài đặt Brython đã cung cấp cho bạn một số manh mối cấp cao về cách hoạt động của quá trình triển khai. Dưới đây là tóm tắt về một số đặc điểm mà bạn đã khám phá cho đến nay trong hướng dẫn này
- Đó là một triển khai Python trong JavaScript
- Đó là trình dịch Python sang JavaScript và thực thi thời gian chạy trong trình duyệt
- Nó hiển thị hai thư viện chính có sẵn dưới dạng tệp JavaScript
01 là cốt lõi của ngôn ngữ Brython, được trình bày chi tiết trong1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
27 là1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
- Nó gọi
02, biên dịch mã Python có trong các thẻ1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
61 với loại1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
041from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
Trong các phần sau, bạn sẽ có cái nhìn chi tiết hơn về cách hoạt động của Brython
Remove adsThành phần cốt lõi của Brython
Cốt lõi của Brython được chứa trong
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
01 hoặc trong 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
70, phiên bản thu nhỏ của động cơ Brython. Cả hai đều bao gồm các thành phần chính sau
02 là hàm JavaScript chính được hiển thị trong không gian tên toàn cục JavaScript. Bạn không thể thực thi bất kỳ mã Python nào mà không gọi hàm này. Đây là chức năng JavaScript duy nhất mà bạn phải gọi rõ ràng1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
72 là một đối tượng toàn cầu JavaScript chứa tất cả các đối tượng bên trong cần thiết để chạy các tập lệnh Python. Đối tượng này không được sử dụng trực tiếp khi bạn viết ứng dụng Brython. Nếu bạn xem mã Brython, cả JavaScript và Python, thì bạn sẽ thấy sự xuất hiện thường xuyên của1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
72. Bạn không cần sử dụng đối tượng này, nhưng bạn nên biết về nó khi gặp lỗi hoặc khi bạn muốn gỡ lỗi mã của mình trong bảng điều khiển trình duyệt1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
Các loại tích hợp là các triển khai của các loại tích hợp Python trong JavaScript. Ví dụ: py_int. js, py_string. js và py_dicts. js là các triển khai tương ứng của và
05 là mô-đun trình duyệt hiển thị các đối tượng JavaScript thường được sử dụng trong ứng dụng web mặt trước, như giao diện DOM sử dụng1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
44 và cửa sổ trình duyệt sử dụng đối tượng1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
791from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
Bạn sẽ thấy từng thành phần này hoạt động khi bạn làm việc qua các ví dụ trong hướng dẫn này
Thư viện tiêu chuẩn Brython
Bây giờ bạn đã có ý tưởng tổng thể về tệp Brython cốt lõi,
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
01, bạn sẽ tìm hiểu về tệp đồng hành của nó, 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
27 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
27 hiển thị thư viện chuẩn Python. Khi tệp này được tạo, Brython biên dịch thư viện chuẩn Python thành JavaScript và nối kết quả vào gói 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
27Brython được dự định càng gần càng tốt với CPython, triển khai tham chiếu Python. Để biết thêm thông tin về CPython, hãy xem Hướng dẫn của bạn về Mã nguồn CPython và Nội bộ CPython
Vì Brython đang chạy trong ngữ cảnh của trình duyệt web nên nó có một số hạn chế. Ví dụ: trình duyệt không cho phép truy cập trực tiếp vào hệ thống tệp, do đó, không thể mở tệp bằng
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
84. Các chức năng không liên quan đến trình duyệt web có thể không được triển khai. Ví dụ: mã bên dưới đang chạy trong môi trường Brython>>>
{"code":"fr","hello":"Salut"}
1đưa ra một ngoại lệ vì việc xóa một tệp cục bộ khỏi môi trường trình duyệt là không an toàn và API Mục nhập Tệp và Thư mục chỉ là một đề xuất dự thảo
Brython chỉ hỗ trợ các mô-đun Python gốc. Nó không hỗ trợ các mô-đun Python được xây dựng bằng C trừ khi chúng được triển khai lại bằng JavaScript. Ví dụ:
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
86 được viết bằng C trong CPython và được triển khai bằng JavaScript trong Brython. Bạn có thể tham khảo danh sách các mô-đun trong bản phân phối Brython để so sánh với việc triển khai CPythonBạn cần bao gồm
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
27 hoặc 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
88 để nhập các mô-đun từ thư viện chuẩn PythonBrython trong hành động
Tại thời điểm này, bạn có thể tự hỏi Brython hoạt động như thế nào trong một trình duyệt chỉ biết đến công cụ JavaScript của nó. Sử dụng lại các ví dụ trước và các công cụ có sẵn trong trình duyệt, bạn sẽ tìm hiểu về quy trình liên quan đến việc thực thi mã Python trong trình duyệt
Trong phần trên, bạn đã xem ví dụ sau
{"code":"fr","hello":"Salut"}
2Khi tải và phân tích cú pháp trang HTML,
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
02 thực hiện các bước sau- Đọc mã Python có trong phần tử
901from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
- Biên dịch mã Python thành JavaScript tương đương
- Đánh giá mã JavaScript kết quả với
911from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
Trong ví dụ trên, mã Python được nhúng trong tệp HTML
{"code":"fr","hello":"Salut"}
3Một tùy chọn khác là tải xuống mã Python từ một tệp riêng
{"code":"fr","hello":"Salut"}
4Trong trường hợp này, tệp Python sẽ trông như thế này
{"code":"fr","hello":"Salut"}
5Tách mã Python khỏi mã HTML là một cách tiếp cận rõ ràng hơn và cho phép bạn tận dụng các lợi ích và chức năng của trình chỉnh sửa mã. Hầu hết các trình soạn thảo đều hỗ trợ JavaScript nhúng trong HTML, nhưng chúng không hỗ trợ Python nội tuyến trong HTML
Remove adsNội bộ của Brython
Phần này cung cấp thông tin chi tiết hơn về quá trình chuyển đổi mã Python thành JavaScript. Nếu bạn không quan tâm đến những chi tiết này, xin vui lòng bỏ qua phần này, vì nó không cần thiết để hiểu phần còn lại của hướng dẫn. Để minh họa quy trình này và xem qua nội bộ của Brython, hãy thực hiện các bước sau
- Mở trang chủ Brython
- Mở bảng điều khiển web bằng Cmd + Alt + . I on Mac or Ctrl+Shift+I on Windows and Linux.
Trong trình duyệt JavaScript REPL, nhập và thực thi đoạn mã sau
{"code":"fr","hello":"Salut"}
6 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
92 phân tích cú pháp và biên dịch mã Python được cung cấp thành JavaScript, sau đó thực thi JavaScript trong trình duyệt web. Bạn sẽ nhận được kết quả sauÁp dụng
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
91 cho bản in mã Brython 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
94 trong bảng điều khiển trình duyệt. Hàm JavaScript trả về 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
95, đây là giá trị trả về mặc định cho một hàm trong JavaScriptKhi xây dựng một ứng dụng Brython, bạn không cần phải gọi rõ ràng một hàm trong mô-đun JavaScript
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
72. Ví dụ này chỉ được cung cấp để chứng minh cách Brython hoạt động đằng sau hậu trường. Biết về 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
72 có thể giúp bạn đọc mã Brython và thậm chí đóng góp cho dự án khi bạn có thêm kinh nghiệm. Nó cũng sẽ giúp bạn hiểu rõ hơn về các trường hợp ngoại lệ có thể được hiển thị trong bảng điều khiển của trình duyệtĐối tượng JavaScript
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
72 có sẵn trong phạm vi toàn cầu của JavaScript và bạn có thể truy cập nó bằng bảng điều khiển JavaScript của trình duyệtSử dụng Brython trong Trình duyệt
Tại thời điểm này, bạn đã có đủ hiểu biết về Brython để làm việc với các ví dụ chi tiết hơn. Trong phần này, bạn sẽ triển khai máy tính Base64 để thử nghiệm trong trình duyệt với API DOM và các chức năng khác thường chỉ có sẵn từ JavaScript
Bạn có thể tải xuống mã nguồn cho các ví dụ trong hướng dẫn này bằng cách nhấp vào liên kết bên dưới
Get the Source Code. Click here to get the source code you’ll use to learn about using Brython to run Python in the browser in this tutorial
Bạn sẽ bắt đầu bằng cách học cách thao tác DOM bằng Python và HTML
API DOM ở Brython
Để thử nghiệm các thao tác DOM có sẵn trong Brython, bạn sẽ tạo một biểu mẫu để mã hóa một chuỗi thành Base64. Mẫu hoàn thành sẽ trông như thế này
Tạo tệp HTML sau và đặt tên là
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
08{"code":"fr","hello":"Salut"}
7HTML ở trên tải các tài nguyên tĩnh, xác định bố cục giao diện người dùng và bắt đầu quá trình biên dịch Python
Dòng 7 tải biểu định kiểu PureCSS để cải thiện kiểu HTML mặc định. Điều này không cần thiết để Brython làm việc
Dòng 9 tải phiên bản thu nhỏ của công cụ Brython
Dòng 12 tải phiên bản thu nhỏ của thư viện chuẩn Brython
Dòng 14 tải
00, xử lý logic động của trang HTML tĩnh này. Lưu ý việc sử dụng{"code":"fr","hello":"Salut"}
01. Nó giúp đồng bộ hóa việc tải và đánh giá tài nguyên và đôi khi cần thiết để đảm bảo rằng Brython và bất kỳ tập lệnh Python nào được tải đầy đủ trước khi thực thi{"code":"fr","hello":"Salut"}
021from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
Dòng 21 mô tả trường
03. Trường này lấy chuỗi để mã hóa làm đối số{"code":"fr","hello":"Salut"}
Dòng 22 đến 25 xác định giá trị mặc định
04 kích hoạt logic chính của trang. Bạn có thể thấy logic này được triển khai trong{"code":"fr","hello":"Salut"}
00 bên dưới{"code":"fr","hello":"Salut"}
Dòng 26 định nghĩa một
04 để xóa dữ liệu và thành phần trên trang. Điều này được thực hiện trong{"code":"fr","hello":"Salut"}
00 bên dưới{"code":"fr","hello":"Salut"}
Dòng 29 tuyên bố một
08 dự định là một trình giữ chỗ cho một bảng{"code":"fr","hello":"Salut"}
Mã Python được liên kết,
{"code":"fr","hello":"Salut"}
00, như sau{"code":"fr","hello":"Salut"}
8Mã Python hiển thị định nghĩa hàm gọi lại và cơ chế thao tác DOM
Dòng 1 nhập các mô-đun mà bạn sử dụng để tương tác với DOM và mã API trình duyệt trong
701from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
Nhập dòng 2
11, có sẵn trong thư viện tiêu chuẩn Brython,{"code":"fr","hello":"Salut"}
881from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
Dòng 4 khai báo một từ điển mà bạn sẽ sử dụng để lưu trữ dữ liệu trong suốt thời gian tồn tại của trang HTML
Dòng 6 xác định trình xử lý sự kiện
13, mã hóa giá trị Base64 của văn bản được nhập vào trường đầu vào có ID{"code":"fr","hello":"Salut"}
14. Đây là một hàm gọi lại lấy một sự kiện làm đối số. Đối số này không được sử dụng trong hàm nhưng được yêu cầu trong Brython và là tùy chọn trong JavaScript. Theo quy ước, bạn có thể sử dụng{"code":"fr","hello":"Salut"}
15 làm trình giữ chỗ giả. Một ví dụ về cách sử dụng này được mô tả trong{"code":"fr","hello":"Salut"}
Dòng 7 truy xuất giá trị của phần tử DOM được xác định bằng
14{"code":"fr","hello":"Salut"}
Dòng 18 xác định trình xử lý sự kiện
17, xóa dữ liệu và trình bày dữ liệu trên trang này{"code":"fr","hello":"Salut"}
Dòng 22 định nghĩa
18, lấy dữ liệu có trong{"code":"fr","hello":"Salut"}
19 và hiển thị nó dưới biểu mẫu trên trang{"code":"fr","hello":"Salut"}
Dòng 26 truy xuất phần tử DOM có ID
14{"code":"fr","hello":"Salut"}
Dòng 29 xóa giá trị của phần tử DOM có ID
14{"code":"fr","hello":"Salut"}
Dòng 31 ràng buộc sự kiện
22 của nút{"code":"fr","hello":"Salut"}
23 với{"code":"fr","hello":"Salut"}
13{"code":"fr","hello":"Salut"}
Dòng 32 liên kết sự kiện
22 của nút{"code":"fr","hello":"Salut"}
26 với{"code":"fr","hello":"Salut"}
17{"code":"fr","hello":"Salut"}
Để thao tác với DOM, Brython sử dụng hai toán tử
47 là toán tử mới, dành riêng cho Brython, bổ sung phần tử con vào nút. Bạn có thể xem một vài ví dụ về cách sử dụng này trong1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
18, được định nghĩa ở dòng 22{"code":"fr","hello":"Salut"}
30 thay thế cho{"code":"fr","hello":"Salut"}
31 và thêm các nút anh chị em{"code":"fr","hello":"Salut"}
Bạn có thể thấy cả hai toán tử trong câu lệnh sau được lấy từ
{"code":"fr","hello":"Salut"}
18{"code":"fr","hello":"Salut"}
9Bạn có thể đọc đoạn mã trên là “thêm vào phần tử bảng một phần tử đầu bảng chứa một phần tử hàng của bảng bao gồm hai phần tử ô dữ liệu bảng liền kề. Nó được hiển thị trong trình duyệt dưới dạng mã HTML sau
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
0Mã HTML hiển thị cấu trúc lồng nhau cho hàng tiêu đề của phần tử bảng. Đây là một định dạng dễ đọc hơn của cùng một mã
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
1Để quan sát kết quả trong bảng điều khiển Brython, bạn có thể nhập khối mã sau
>>>
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
2Để thực thi mã đầy đủ, bạn cần khởi động máy chủ web. Như trước đây, bạn khởi động máy chủ web Python tích hợp trong cùng thư mục với hai tệp
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
08 và {"code":"fr","hello":"Salut"}
00 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
3Sau khi khởi động máy chủ web, hãy trỏ trình duyệt của bạn tới
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
34. Trang trông như thế nàyBạn sẽ mở rộng ví dụ này trong phần này bằng cách cho phép dữ liệu được lưu trữ giữa các lần tải lại trang
Remove adsnhập khẩu ở brython
Bạn có thể sử dụng
{"code":"fr","hello":"Salut"}
36 để truy cập các mô-đun Python hoặc mô-đun Brython được biên dịch thành JavaScriptCác mô-đun Python là các tệp có phần mở rộng
{"code":"fr","hello":"Salut"}
37 trong thư mục gốc của dự án của bạn hoặc, đối với gói Python, trong thư mục con chứa tệp {"code":"fr","hello":"Salut"}
38. Để nhập các mô-đun Python vào mã Brython của bạn, bạn cần khởi động một máy chủ web. Để biết thêm về các mô-đun Python, hãy xem Mô-đun và Gói Python – Giới thiệuĐể khám phá cách nhập mô-đun Python vào mã Brython của bạn, hãy làm theo hướng dẫn được mô tả trong phần trên, tạo và kích hoạt môi trường ảo Python, cài đặt Brython và sửa đổi
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
08 như sau 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
4Tệp HTML ở trên hiển thị các mô-đun được nhập từ công cụ lõi [
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
05], từ thư viện chuẩn [_______13_______41] và từ mô-đun Python cục bộ [{"code":"fr","hello":"Salut"}
42]. Đây là nội dung của {"code":"fr","hello":"Salut"}
43 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
5Mô-đun này thực hiện
{"code":"fr","hello":"Salut"}
44, một trong những. {"code":"fr","hello":"Salut"}
44 trả về n phần tử đầu tiên của một lần lặp đã cho. Nó dựa trên {"code":"fr","hello":"Salut"}
47If you try to open
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
08 from the file system with your browser, then you’ll get the following error in the browser console 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
6Nhập mô-đun Python yêu cầu khởi động máy chủ web cục bộ. Bắt đầu một máy chủ web cục bộ và trỏ trình duyệt của bạn tới
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
34. Bạn sẽ thấy trang HTML sauVới một máy chủ web đang chạy, trình duyệt có thể tìm nạp mô-đun
{"code":"fr","hello":"Salut"}
43 khi {"code":"fr","hello":"Salut"}
51 được thực thi. Kết quả của cả hai giá trị, {"code":"fr","hello":"Salut"}
52 và {"code":"fr","hello":"Salut"}
53, được chèn vào tệp HTML bằng hai dòng cuối cùng của tập lệnh Python được nhúng và được trình duyệt hiển thịGiảm kích thước nhập khẩu
Trong thư mục dự án của ví dụ trước, để giảm kích thước của các mô-đun JavaScript đã nhập và để biên dịch trước các mô-đun Python thành JavaScript, bạn có thể sử dụng
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
16 với tùy chọn {"code":"fr","hello":"Salut"}
55 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
7Điều này sẽ tạo ra
{"code":"fr","hello":"Salut"}
56 và bạn có thể sửa đổi phần tử 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
11 của 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
08 như sau 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
8Dòng 4 thay đổi nguồn kịch bản ban đầu từ
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
27 thành {"code":"fr","hello":"Salut"}
56Mở
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
08 bằng trình duyệt của bạn hoặc trỏ trình duyệt đến máy chủ cục bộ sẽ hiển thị cùng một trang HTML. Lưu ý những điểm sau- Bạn có thể hiển thị trang HTML trong trình duyệt của mình mà không cần chạy máy chủ web
- Bạn không cần phân phối
43 vì mã này đã được chuyển đổi thành JavaScript và được đóng gói trong{"code":"fr","hello":"Salut"}
56{"code":"fr","hello":"Salut"}
- Bạn không cần tải
271from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
Công cụ dòng lệnh
{"code":"fr","hello":"Salut"}
65 cung cấp giải pháp xóa mã không cần thiết khỏi thư viện chuẩn và biên dịch mô-đun python của bạn thành mã JavaScript. Điều này giúp đóng gói ứng dụng của bạn và dẫn đến việc tải xuống tài nguyên nhỏ hơnGhi chú. Tương tự như việc nhập mô-đun Python, việc tải mô-đun Python bằng phần tử HTML
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
61 yêu cầu bạn khởi động máy chủ web. Hãy xem xét phần tử HTML 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
61 sau đây 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
9Khi chức năng Brython được thực thi và tải nội dung
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
61 trỏ đến tệp Python, nó sẽ cố gắng thực hiện lệnh gọi Ajax chỉ có thể được thực hiện khi máy chủ web đang chạy. Nếu bạn cố mở tệp từ hệ thống tệp thì một lỗi tương tự như sau sẽ hiển thị trong bảng điều khiển JavaScript của trình duyệt{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
0Bảo vệ an ninh ngăn bạn tải
{"code":"fr","hello":"Salut"}
00 từ hệ thống tệp cục bộ. Bạn có thể giải quyết vấn đề này bằng cách chạy một máy chủ tệp cục bộ. Để biết thêm thông tin về hành vi này, hãy xem tài liệu BrythonRemove adsTương tác với JavaScript
Brython cho phép mã Python tương tác với mã JavaScript. Mẫu phổ biến nhất là truy cập JavaScript từ Brython. Điều ngược lại, mặc dù có thể xảy ra, nhưng không phổ biến. Bạn sẽ thấy một ví dụ về JavaScript gọi một hàm Python trong phần
JavaScript
Cho đến thời điểm này, bạn đã trải qua một vài tình huống trong đó mã Python tương tác với mã JavaScript. Đặc biệt, bạn đã có thể hiển thị hộp thông báo bằng cách gọi
{"code":"fr","hello":"Salut"}
70Bạn có thể thấy hoạt động của
{"code":"fr","hello":"Salut"}
71 trong ba ví dụ sau đang chạy trong bảng điều khiển Brython, không phải trong trình biên dịch CPython tiêu chuẩn>>>
{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
1Hoặc bạn có thể sử dụng
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
79>>>
{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
2Hoặc bạn có thể sử dụng
{"code":"fr","hello":"Salut"}
73>>>
{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
3Do lớp mới được hiển thị bởi Brython và bản chất toàn cầu của cả
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
06 và 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
79, bạn có thể gọi {"code":"fr","hello":"Salut"}
71 trên {"code":"fr","hello":"Salut"}
77 hoặc thậm chí trên {"code":"fr","hello":"Salut"}
78Dưới đây là các mô-đun chính của Brython cho phép truy cập vào các hàm JavaScript
Mô-đunBối cảnhVí dụ
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
05Chứa tên và mô-đun tích hợp{"code":"fr","hello":"Salut"}
70{"code":"fr","hello":"Salut"}
81Truy cập DOM{"code":"fr","hello":"Salut"}
82{"code":"fr","hello":"Salut"}
83{"code":"fr","hello":"Salut"}
84Creates HTML elements{"code":"fr","hello":"Salut"}
85{"code":"fr","hello":"Salut"}
77Accesses {"code":"fr","hello":"Salut"}
87 functions and objects{"code":"fr","hello":"Salut"}
88{"code":"fr","hello":"Salut"}
89{"code":"fr","hello":"Salut"}
90Accesses objects defined in JavaScript{"code":"fr","hello":"Salut"}
91{"code":"fr","hello":"Salut"}
92Ngoài các hàm JavaScript và API có sẵn trong trình duyệt, bạn cũng có thể truy cập vào các hàm JavaScript mà bạn đã viết. Ví dụ sau minh họa cách truy cập hàm JavaScript tùy chỉnh từ Brython
{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
4Đây là cách nó hoạt động
- Dòng 9 định nghĩa hàm tùy chỉnh
93 trong khối JavaScript{"code":"fr","hello":"Salut"}
- Dòng 17 gọi
93{"code":"fr","hello":"Salut"}
Bạn có thể sử dụng tính năng tương tự để truy cập các thư viện JavaScript. Bạn sẽ thấy cách thức trong phần , nơi bạn sẽ tương tác với Vue. js, một khung giao diện người dùng web phổ biến
API trình duyệt web
Trình duyệt hiển thị API web mà bạn có thể truy cập từ JavaScript và Brython có quyền truy cập vào cùng API. Trong phần này, bạn sẽ mở rộng máy tính Base64 để lưu trữ dữ liệu giữa các lần tải lại trang trình duyệt
API web cho phép tính năng này là API lưu trữ web. Nó bao gồm hai cơ chế
95{"code":"fr","hello":"Salut"}
96{"code":"fr","hello":"Salut"}
Bạn sẽ sử dụng
{"code":"fr","hello":"Salut"}
96 trong ví dụ sắp tớiNhư bạn đã biết trước đó, máy tính Base64 tạo một từ điển chứa chuỗi đầu vào được ánh xạ tới giá trị được mã hóa Base64 của chuỗi này. Dữ liệu vẫn còn trong bộ nhớ sau khi trang được tải nhưng sẽ bị xóa khi bạn tải lại trang. Lưu dữ liệu vào
{"code":"fr","hello":"Salut"}
96 sẽ giữ nguyên từ điển giữa các lần tải lại trang. {"code":"fr","hello":"Salut"}
96 là kho lưu trữ khóa-giá trịĐể truy cập
{"code":"fr","hello":"Salut"}
96, bạn cần nhập 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
01. Để theo kịp quá trình triển khai ban đầu, bạn sẽ tải và lưu dữ liệu từ điển vào {"code":"fr","hello":"Salut"}
96 ở định dạng JSON. Chìa khóa để lưu và tìm nạp dữ liệu sẽ là 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
03. Mã đã sửa đổi bao gồm các lần nhập mới và hàm 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
04{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
5 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
04 được thực thi khi mã Python được tải. Nó tìm nạp dữ liệu JSON từ {"code":"fr","hello":"Salut"}
96 và điền vào một từ điển Python sẽ được sử dụng để giữ dữ liệu trong bộ nhớ trong suốt vòng đời của trang. If it doesn’t find 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
03 in {"code":"fr","hello":"Salut"}
96, then it creates an empty dictionary for key 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
03 in {"code":"fr","hello":"Salut"}
96 and returns an empty dictionaryBạn có thể xem mã Python đầy đủ kết hợp với
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
04 bằng cách mở rộng hộp bên dưới. Nó cho thấy cách sử dụng API web {"code":"fr","hello":"Salut"}
96 làm bộ lưu trữ liên tục thay vì dựa vào bộ nhớ tạm thời trong bộ nhớ, như trong lần triển khai trước của ví dụ nàyMã nguồn hoàn chỉnh với quyền truy cập vào localStorageHiển thị/Ẩn
Đoạn mã sau cho biết cách quản lý dữ liệu bằng trình duyệt
{"code":"fr","hello":"Salut"}
96{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
6Các dòng mới được đánh dấu. Từ điển toàn cầu
{"code":"fr","hello":"Salut"}
19 được điền bởi 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
04 khi tệp được tải và xử lý khi gọi 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
02. Khi trang được tải lại, dữ liệu được lấy từ {"code":"fr","hello":"Salut"}
96Mỗi khi một giá trị Base64 mới được tính toán, nội dung của
{"code":"fr","hello":"Salut"}
19 được chuyển đổi thành JSON và được lưu trữ trong bộ lưu trữ cục bộ. Chìa khóa của kho lưu trữ là 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
03Bạn có thể truy cập tất cả các chức năng API web từ
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
05 và các mô-đun con khác. Tài liệu cấp cao về cách truy cập API web có sẵn trong tài liệu Brython. Để biết thêm chi tiết, bạn có thể tham khảo tài liệu API web và sử dụng bảng điều khiển Brython để thử nghiệm các API webTrong một số trường hợp, bạn có thể phải chọn giữa các hàm Python quen thuộc và các hàm từ API web. Ví dụ: trong mã ở trên, bạn sử dụng mã hóa Python Base64,
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
21, nhưng bạn có thể đã sử dụng mã hóa của JavaScript 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
22>>>
{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
7Bạn có thể kiểm tra cả hai biến thể trong bảng điều khiển trực tuyến. Việc sử dụng
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
23 sẽ chỉ hoạt động trong ngữ cảnh Brython, trong khi đó, 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
21 có thể được thực thi với triển khai Python thông thường như CPython. Lưu ý rằng trong phiên bản CPython, 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
21 lấy a làm loại đối số, trong khi JavaScript 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
23 lấy một chuỗiNếu hiệu suất là mối quan tâm, thì hãy cân nhắc sử dụng phiên bản JavaScript
Remove adsKhung giao diện người dùng web
Các khung giao diện người dùng JavaScript phổ biến như Angular, React, Vue. js hoặc Svelte đã trở thành một phần quan trọng trong bộ công cụ dành cho nhà phát triển giao diện người dùng và Brython tích hợp hoàn hảo với một số khung này. Trong phần này, bạn sẽ xây dựng một ứng dụng bằng Vue. js phiên bản 3 và Brython
Ứng dụng bạn sẽ xây dựng là một biểu mẫu tính toán giá trị băm của một chuỗi. Đây là ảnh chụp màn hình của trang HTML đang chạy
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
28 của trang HTML xác định các liên kết và mẫu một cách khai báo{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
8Nếu bạn không quen thuộc với Vue, thì bạn sẽ nhanh chóng tìm hiểu một số điều bên dưới, nhưng vui lòng tham khảo tài liệu chính thức để biết thêm thông tin
- Vue. js là các giá trị thuộc tính đặc biệt, có tiền tố là
29, cung cấp hành vi động và ánh xạ dữ liệu giữa các giá trị của DOM và Vue. thành phần js1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
30 liên kết giá trị đầu vào với1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
31 và cắt giá trị1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
32 liên kết giá trị của danh sách thả xuống với1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
331from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
34 liên kết giá trị tùy chọn với1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
351from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
- Các mẫu Vue được biểu thị bằng các biến được bao quanh bởi dấu ngoặc nhọn kép. Vue. js thay thế các trình giữ chỗ tương ứng bằng giá trị tương ứng trong thành phần Vue
361from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
351from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
- Trình xử lý sự kiện được xác định bằng ký hiệu at [
38] như trong1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
391from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
Mã Python tương ứng mô tả Vue và logic nghiệp vụ kèm theo
{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
9Bản chất khai báo của Vue. js được hiển thị trong tệp HTML với các mẫu và chỉ thị Vue. Nó cũng được thể hiện trong mã Python với khai báo thành phần Vue trên dòng 11 và dòng 28 đến 35. Kỹ thuật khai báo này kết nối các giá trị nút của DOM với dữ liệu Vue, cho phép hành vi của khung
Điều này giúp loại bỏ một số mã soạn sẵn mà bạn phải viết trong ví dụ trước. Chẳng hạn, lưu ý rằng bạn không phải chọn các phần tử từ DOM với biểu thức như
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
40. Tạo ứng dụng Vue và gọi 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
41 xử lý ánh xạ của thành phần Vue tới các phần tử DOM tương ứng và liên kết của các hàm JavaScriptTrong Python, việc truy cập các trường đối tượng Vue yêu cầu bạn tham chiếu đến đối tượng Vue bằng
{"code":"fr","hello":"Salut"}
91- Dòng 14 lấy giá trị của trường thành phần
431from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
- Dòng 21 cập nhật thành phần dữ liệu
441from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
- Dòng 25 thêm một thuật toán vào danh sách
451from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
- Dòng 26 khởi tạo
46 bằng khóa đầu tiên của1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
471from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
Nếu phần giới thiệu Vue kết hợp với Brython này đã thu hút sự quan tâm của bạn, thì bạn có thể muốn xem dự án vuepy, cung cấp đầy đủ các liên kết Python cho Vue. js và sử dụng Brython để chạy Python trong trình duyệt
WebLắp ráp
Trong một số trường hợp, bạn có thể sử dụng WebAssugging để cải thiện hiệu suất của Brython hoặc thậm chí là JavaScript. WebAssembly, hay Wasm, là mã nhị phân được hỗ trợ bởi tất cả các trình duyệt chính. Nó có thể cải thiện hiệu suất so với JavaScript trong trình duyệt và là mục tiêu biên dịch cho các ngôn ngữ như C, C++ và Rust. Nếu bạn không sử dụng Rust hoặc Wasm, thì bạn có thể bỏ qua phần này
Trong ví dụ sau minh họa cách sử dụng WebAssugging, bạn sẽ triển khai một hàm trong Rust và sẽ gọi nó từ Python
Đây không phải là một hướng dẫn kỹ lưỡng về Rust. Nó chỉ làm trầy xước bề mặt. Để biết thêm chi tiết về Rust, hãy xem tài liệu về Rust
Bắt đầu bằng cách cài đặt Rust bằng cách sử dụng
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
48. Để biên dịch các tệp Wasm, bạn cũng cần thêm mục tiêu 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
49>>> import uuid
0Tạo một dự án bằng cách sử dụng
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
50, được cài đặt trong quá trình cài đặt Rust>>> import uuid
1Lệnh trên tạo một dự án khung trong thư mục có tên
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
51. Trong thư mục này, bạn sẽ tìm thấy 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
52, tệp cấu hình bản dựng Rust mà bạn cần sửa đổi để cho biết rằng bạn muốn tạo một thư viện động. Bạn có thể làm điều này bằng cách thêm phần được đánh dấu>>> import uuid
2Sửa đổi
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
53 bằng cách thay thế nội dung của nó bằng nội dung sau>>> import uuid
3Trong thư mục gốc của dự án, nơi có
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
52, hãy biên dịch dự án của bạn>>> import uuid
4Tiếp theo, tạo một thư mục
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
20 với 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
08 sau>>> import uuid
5Dòng 6 ở trên tải
{"code":"fr","hello":"Salut"}
00 sau từ cùng một thư mục>>> import uuid
6Các dòng được đánh dấu là chất keo cho phép Brython truy cập chức năng Rust
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
58- Dòng 16 đọc
59 bằng cách sử dụng1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
60 và sau đó gọi1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
61 khi tệp Wasm được tải xuống1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
- Dòng 5 triển khai
61, lấy mô-đun Wasm làm đối số1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
- Dòng 7 gán
58 cho tên địa phương1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
64 để cung cấp cho Python1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
Trong cùng thư mục
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
20, sao chép 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
59 từ 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
67>>> import uuid
7Bố cục thư mục dự án trông như thế này
>>> import uuid
8Điều này cho thấy cấu trúc thư mục của dự án Rust được tạo bằng
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
68. Để rõ ràng, 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
69 được lược bỏ một phầnBây giờ hãy bắt đầu một máy chủ trong
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
20 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
3Cuối cùng, trỏ trình duyệt Internet của bạn tới
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
34. Trình duyệt của bạn sẽ hiển thị một trang như sauDự án này cho thấy cách tạo một WebAssembly mà bạn có thể sử dụng từ JavaScript hoặc Brython. Do chi phí hoạt động đáng kể phát sinh từ việc xây dựng tệp Wasm, đây không phải là cách tiếp cận đầu tiên của bạn để giải quyết một vấn đề cụ thể
Nếu JavaScript không đáp ứng các yêu cầu về hiệu suất của bạn, thì Rust có thể là một lựa chọn. Điều này chủ yếu hữu ích nếu bạn đã có mã Wasm để tương tác, mã bạn đã tạo hoặc thư viện Wasm hiện có
Một lợi ích khác có thể có của việc sử dụng Rust để tạo WebAssugging là khả năng truy cập vào các thư viện không tồn tại trong Python hoặc JavaScript. Nó cũng có thể hữu ích nếu bạn muốn sử dụng thư viện Python được viết bằng C và không thể sử dụng với Brython. Nếu một thư viện như vậy tồn tại trong Rust, thì bạn có thể xem xét việc tạo một tệp Wasm để sử dụng nó với Brython
Áp dụng phát triển không đồng bộ ở Brython
Lập trình đồng bộ là hành vi tính toán mà bạn có thể quen thuộc nhất. Ví dụ: khi thực hiện ba câu lệnh A, B và C, chương trình sẽ thực hiện A trước, sau đó là B và cuối cùng là C. Mỗi câu lệnh chặn dòng chảy của chương trình trước khi chuyển nó sang câu lệnh tiếp theo
Hãy tưởng tượng một kỹ thuật mà A sẽ được thực thi trước, B sẽ được gọi nhưng không được thực thi ngay lập tức và sau đó C sẽ được thực thi. Bạn có thể nghĩ về B như một việc được thực hiện trong tương lai. Vì B không bị chặn nên nó được coi là không đồng bộ. Để biết thêm thông tin cơ bản về lập trình không đồng bộ, bạn có thể xem Bắt đầu với các tính năng không đồng bộ trong Python
JavaScript đang và dựa vào quá trình xử lý không đồng bộ, đặc biệt khi có liên quan đến truyền thông mạng. Ví dụ: tìm nạp kết quả của API không yêu cầu chặn việc thực thi các chức năng JavaScript khác
Với Brython, bạn có quyền truy cập vào các tính năng không đồng bộ thông qua một số thành phần
- gọi lại JavaScript
721from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
731from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
Khi JavaScript đã phát triển, các cuộc gọi lại đã dần dần được thay thế bằng các lời hứa hoặc chức năng không đồng bộ. Trong hướng dẫn này, bạn sẽ học cách sử dụng các lời hứa từ Brython và cách sử dụng các mô-đun
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
72 và 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
73, những mô-đun tận dụng bản chất không đồng bộ của JavaScriptKhông thể sử dụng mô-đun
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
76 từ thư viện CPython trong ngữ cảnh trình duyệt và được thay thế trong Brython bằng 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
73Lời hứa JavaScript ở Brython
Trong JavaScript, một lời hứa là một đối tượng có thể tạo ra kết quả trong tương lai. Giá trị được tạo ra sau khi hoàn thành sẽ là giá trị hoặc lý do xảy ra lỗi
Đây là một ví dụ minh họa cách sử dụng đối tượng JavaScript
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
78 từ Brython. Bạn có thể làm việc với ví dụ này trong bảng điều khiển trực tuyến>>>
>>> uuid.uuid4[]
UUID['291930f9-0c79-4c24-85fd-f76f2ada0b2a']
0Trong bảng điều khiển web, bạn có thể nhận phản hồi ngay lập tức về việc thực thi mã Python
- Dòng 1 nhập
79 để đặt thời gian chờ và1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
79 để truy cập đối tượng1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
781from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
- Dòng 2 định nghĩa một bộ thực thi,
82, trả về một thông báo khi lời hứa thành công, khi hết thời gian chờ1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
- Dòng 5 định nghĩa một chức năng,
83, hiển thị cảnh báo1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
- Dòng 8 tạo một lời hứa với người thực hiện, được xâu chuỗi bằng khối
84, cho phép truy cập vào kết quả của lời hứa1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
Trong ví dụ trên, thời gian chờ mô phỏng giả tạo một chức năng chạy dài. Việc sử dụng thực sự một lời hứa có thể liên quan đến một cuộc gọi mạng. Sau
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
85 giây, lời hứa hoàn thành thành công với giá trị 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
86Nếu chức năng thực thi,
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
82, phát hiện lỗi, thì nó có thể gọi 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
88 với lý do lỗi làm đối số. Bạn có thể thực hiện điều này bằng một phương thức chuỗi mới, 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
89, trên đối tượng 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
78, như sau>>>
>>> uuid.uuid4[]
UUID['291930f9-0c79-4c24-85fd-f76f2ada0b2a']
1Bạn có thể thấy hành vi hoàn thành thành công lời hứa trong hình ảnh sau
Khi bạn chạy mã trong bảng điều khiển, bạn có thể thấy rằng đối tượng
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
78 được tạo trước và sau khi hết thời gian chờ, hộp thông báo sẽ hiển thịAjax ở Brython
Các hàm không đồng bộ đặc biệt hữu ích khi các hàm đủ điều kiện là ràng buộc I/O. Điều này trái ngược với các chức năng gắn với CPU. Chức năng liên kết I/O là chức năng dành phần lớn thời gian chờ đầu vào hoặc đầu ra kết thúc, trong khi chức năng liên kết CPU là tính toán. Gọi một API qua mạng hoặc truy vấn cơ sở dữ liệu là một thao tác thực thi theo giới hạn I/O, trong khi việc tính toán một chuỗi các số nguyên tố là do CPU giới hạn
Brython's
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
72 hiển thị các hàm HTTP như 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
93 và 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
94, theo mặc định, là không đồng bộ. Các chức năng này nhận tham số import antigravity
9 có thể được đặt thành import antigravity
4 để hiển thị đồng bộ chức năng tương tựĐể gọi HTTP
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
97 không đồng bộ, hãy gọi import antigravity
7 như sau>>> uuid.uuid4[]
UUID['291930f9-0c79-4c24-85fd-f76f2ada0b2a']
2Để tìm nạp API ở chế độ chặn, hãy đặt tham số
import antigravity
9 thành import antigravity
4>>> uuid.uuid4[]
UUID['291930f9-0c79-4c24-85fd-f76f2ada0b2a']
3Đoạn mã sau cho thấy sự khác biệt giữa việc thực hiện lệnh gọi Ajax chặn và lệnh gọi Ajax không chặn
>>> uuid.uuid4[]
UUID['291930f9-0c79-4c24-85fd-f76f2ada0b2a']
4Đoạn mã trên minh họa cả hai hành vi, đồng bộ và không đồng bộ
Dòng 13 định nghĩa
01, tìm nạp văn bản từ một tệp từ xa bằng cách sử dụng{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
7. Hành vi mặc định củaimport antigravity
7 là không đồng bộ.import antigravity
01 trả về và{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
05 được gán cho tham số{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
06 được gọi lại sau khi nhận được tệp từ xa{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
07{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
Dòng 18 định nghĩa
08, trình bày cách sử dụng{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
7 với hành vi chặn. Trong kịch bản này,import antigravity
05 được gọi trước khi{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
08 trả về{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
Khi bạn chạy ví dụ đầy đủ và nhấp vào Nhận không đồng bộ và Nhận chặn, bạn sẽ thấy màn hình sau
Bạn có thể thấy rằng trong kịch bản đầu tiên,
{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
01 được thực thi đầy đủ và kết quả của lệnh gọi API diễn ra không đồng bộ. Trong tình huống thứ hai, kết quả của lệnh gọi API được hiển thị trước khi quay lại từ {
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
08IO không đồng bộ ở Brython
Với
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
76, Python 3. 4 bắt đầu bộc lộ các khả năng không đồng bộ mới. Trong Trăn 3. 5, hỗ trợ không đồng bộ đã được làm phong phú thêm với. Do không tương thích với vòng lặp sự kiện của trình duyệt, Brython triển khai 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
73 để thay thế cho tiêu chuẩn 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
76Mô-đun Brython
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
73 và mô-đun Python 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
76 đều hỗ trợ sử dụng các từ khóa {
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
15 và {
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
16 và chia sẻ các chức năng chung, chẳng hạn như {
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
23 và {
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
24. Cả hai mô-đun đều triển khai các chức năng riêng biệt khác liên quan đến ngữ cảnh thực thi tương ứng của chúng, môi trường ngữ cảnh CPython cho 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
76 và môi trường trình duyệt cho 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
73quân đoàn
Bạn có thể sử dụng
{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
23 và {
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
24 để tạo. Để minh họa hành vi của các coroutine được triển khai trong Brython, bạn sẽ triển khai một biến thể của ví dụ coroutine có sẵn trong>>> uuid.uuid4[]
UUID['291930f9-0c79-4c24-85fd-f76f2ada0b2a']
5Ngoại trừ dòng
{"code":"fr","hello":"Salut"}
36 đầu tiên, mã này giống với mã bạn tìm thấy trong tài liệu CPython. Nó thể hiện việc sử dụng các từ khóa {
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
15 và {
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
16 và cho thấy {
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
23 và {
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
24 trong hành động- Dòng 1 sử dụng
76 làm bí danh cho1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
73. Mặc dù nó che khuất1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
36, nhưng nó giữ mã gần với ví dụ về tài liệu Python để tạo điều kiện so sánh{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
- Dòng 4 khai báo quy trình đăng ký
37. Lưu ý việc sử dụng{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
15{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
- Dòng 5 gọi
39 với{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
16 để chức năng hiện tại sẽ nhường quyền kiểm soát cho chức năng khác cho đến khi hoàn thành{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
24{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
- Dòng 8 tuyên bố một coroutine khác sẽ tự gọi coroutine
37 hai lần{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
- Dòng 9 gọi
23, một hàm nonblocking lấy một coroutine—{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
44 trong ví dụ này—làm đối số{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
Lưu ý rằng trong ngữ cảnh của trình duyệt,
{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
45 tận dụng vòng lặp sự kiện JavaScript bên trong. Hàm này khác với hàm liên quan {
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
46 trong CPython, hàm này quản lý hoàn toàn vòng lặp sự kiệnĐể thực thi mã này, hãy dán mã vào trình chỉnh sửa Brython trực tuyến và nhấp vào Chạy. Bạn sẽ nhận được kết quả tương tự như ảnh chụp màn hình sau
Đầu tiên, tập lệnh được thực thi, sau đó hiển thị
{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
47 và cuối cùng hiển thị {
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
48Để biết thêm chi tiết về coroutines trong Python, bạn có thể xem Async IO trong Python. Hướng dẫn hoàn chỉnh
Các khái niệm chung về I/O không đồng bộ áp dụng cho tất cả các nền tảng bao gồm mẫu này. Trong JavaScript, vòng lặp sự kiện thực chất là một phần của môi trường, trong khi ở CPython, đây là thứ được quản lý bằng cách sử dụng các hàm được hiển thị bởi
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
76Ví dụ trên là một bài tập có chủ ý để giữ mã chính xác như trong ví dụ về tài liệu Python. Trong khi viết mã trong trình duyệt bằng Brython, bạn nên sử dụng rõ ràng
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
73, như bạn sẽ thấy trong phần sauCác chức năng dành riêng cho web
Để thực hiện lệnh gọi không đồng bộ tới API, như trong phần trước, bạn có thể viết một hàm như sau
>>> uuid.uuid4[]
UUID['291930f9-0c79-4c24-85fd-f76f2ada0b2a']
6Lưu ý việc sử dụng các từ khóa
{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
15 và {
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
16. Chức năng cần được xác định là {
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
15 để sử dụng cuộc gọi với {
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
16. Trong quá trình thực hiện chức năng này, khi đạt đến cuộc gọi tới {
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
55, chức năng này sẽ trao quyền điều khiển trở lại vòng lặp sự kiện chính trong khi chờ cuộc gọi mạng, {
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
56, hoàn tất. Phần còn lại của việc thực hiện chương trình không bị chặnĐây là một ví dụ về cách gọi
{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
57>>> uuid.uuid4[]
UUID['291930f9-0c79-4c24-85fd-f76f2ada0b2a']
7Hàm
{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
45 thực thi quy trình đăng quang {
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
57. Nó không chặnMột ví dụ mã hoàn chỉnh hơn cho thấy cách sử dụng các từ khóa
{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
15 và {
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
16 và cách mà ____17_______45 và {
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
56 bổ sung cho nhau>>> uuid.uuid4[]
UUID['291930f9-0c79-4c24-85fd-f76f2ada0b2a']
8Như trong các phiên bản Python 3 gần đây nhất, bạn có thể sử dụng các từ khóa
{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
15 và {
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
16- Dòng 7 định nghĩa
57 với từ khóa{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
15{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
- Dòng 9 gọi
56 với từ khóa{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
16. Sử dụng{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
16 yêu cầu chức năng kèm theo được xác định bằng{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
15{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
- Dòng 14 cho biết cách sử dụng
45, lấy tham số là hàm{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
15 được gọi{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
Để chạy toàn bộ ví dụ, bạn cần khởi động máy chủ web. Bạn có thể khởi động máy chủ web phát triển Python với
{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
74. Nó khởi động một máy chủ web cục bộ trên cổng 8000 và trang mặc định 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
08Ảnh chụp màn hình hiển thị trình tự các bước được thực hiện sau khi nhấp vào Async Get. Sự kết hợp giữa việc sử dụng mô-đun
{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
36 và các từ khóa {
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
15 và {
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
16 cho thấy cách bạn có thể nắm lấy mô hình lập trình không đồng bộ mà JavaScript thúc đẩyPhân phối và đóng gói một dự án Brython
Phương pháp bạn sử dụng để cài đặt Brython có thể ảnh hưởng đến cách thức và vị trí bạn có thể triển khai dự án Brython của mình. Cụ thể, để triển khai lên PyPI, tùy chọn tốt nhất trước tiên là cài đặt Brython từ PyPI, sau đó tạo dự án của bạn với
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
16. Tuy nhiên, việc triển khai web thông thường tới máy chủ riêng hoặc tới nhà cung cấp đám mây có thể tận dụng bất kỳ phương pháp cài đặt nào bạn chọnBạn có một số tùy chọn triển khai
- Triển khai thủ công và tự động
- Triển khai cho PyPI
- Triển khai lên CDN
Bạn sẽ khám phá từng điều này trong các phần sau
Triển khai web thủ công và tự động
Ứng dụng của bạn chứa tất cả các tệp phụ thuộc tĩnh, CSS, JavaScript, Python và tệp hình ảnh mà bạn cần cho trang web của mình. Brython là một phần của tệp JavaScript của bạn. Tất cả các tệp có thể được triển khai nguyên trạng trên nhà cung cấp mà bạn chọn. Bạn có thể tham khảo Hướng dẫn phát triển web và Tự động triển khai Django với Fabric và Ansible để biết chi tiết về cách triển khai các ứng dụng Brython của mình
Nếu bạn quyết định sử dụng
{"code":"fr","hello":"Salut"}
65 để biên dịch trước mã Python của mình, thì các tệp bạn triển khai sẽ không có bất kỳ mã nguồn Python nào, chỉ có 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
01 và {"code":"fr","hello":"Salut"}
56. Bạn cũng sẽ không bao gồm 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
27 vì các mô-đun bắt buộc sẽ được bao gồm trong {"code":"fr","hello":"Salut"}
56 rồiTriển khai cho PyPI
Khi bạn cài đặt Brython từ PyPI, bạn có thể sử dụng
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
16 để tạo gói có thể triển khai cho PyPI. Mục tiêu của việc tạo một gói như vậy là để mở rộng mẫu Brython mặc định làm cơ sở cho các dự án tùy chỉnh của bạn và cung cấp các trang web Brython từ PyPISau khi làm theo hướng dẫn trong phần trên, hãy thực hiện lệnh sau trong dự án
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
20 mới của bạn>>> uuid.uuid4[]
UUID['291930f9-0c79-4c24-85fd-f76f2ada0b2a']
9Bạn sẽ được nhắc trả lời một số câu hỏi nhằm tạo
{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
87, bạn có thể sửa đổi câu hỏi này sau. Sau khi hoàn thành lệnh, bạn sẽ có một thư mục có tên là {
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
88 chứa các tệp bạn cần để tạo gói có thể cài đặtBạn có thể kiểm tra việc cài đặt gói mới này cục bộ như sau
import this
0Sau đó, bạn cũng có thể xác nhận rằng lệnh mới được triển khai cục bộ với gói
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
20 bằng cách thực hiện lệnh sauimport this
1Lưu ý rằng lệnh
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
20 hoạt động chính xác như Brython thực hiện sau lần cài đặt đầu tiên. Bạn vừa tạo gói Brython có thể cài đặt tùy chỉnh có thể được triển khai cho PyPI. Để biết mô tả kỹ lưỡng về cách triển khai gói của bạn lên PyPI, hãy xem Cách xuất bản Gói Python mã nguồn mở lên PyPISau khi triển khai lên PyPI, bạn có thể cài đặt gói Brython của mình với
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
14 trong môi trường ảo Python. Bạn sẽ có thể tạo ứng dụng tùy chỉnh mới của mình bằng lệnh mới mà bạn đã tạoimport this
2Tóm lại, đây là các bước để triển khai lên PyPI
- Cài đặt Brython từ PyPI
- Tạo một dự án với
231from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
- Tạo một gói có thể cài đặt từ dự án của bạn với
93{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
- Triển khai gói này cho PyPI
Các phương thức cài đặt khác—CDN, GitHub và npm—không bao gồm
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
16 và do đó không phù hợp để chuẩn bị gói PyPITriển khai tới CDN
Giống như
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
01 và {
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
96 có sẵn trên máy chủ CDN, bạn cũng có thể triển khai nội dung tĩnh, hình ảnh, kiểu và tệp JavaScript của mình, bao gồm tệp Python hoặc {"code":"fr","hello":"Salut"}
56, cho CDN. Ví dụ về CDN bao gồm- đám mây
- CDN đám mây của Google
- Azure CDN
- Mặt trận đám mây Amazon
- Akamai
Nếu ứng dụng của bạn là mã nguồn mở thì bạn có thể nhận hỗ trợ CDN miễn phí. Ví dụ bao gồm CDNJS và jsDelivr
Tạo tiện ích mở rộng của Google Chrome
Tiện ích mở rộng của Chrome là các thành phần được xây dựng bằng công nghệ web và được tích hợp vào Chrome để tùy chỉnh môi trường duyệt web của bạn. Typically, the icons of these extensions are visible at the top of the Chrome window, to the right of the address bar
Tiện ích mở rộng công khai có sẵn trên cửa hàng Chrome trực tuyến. Để tìm hiểu, bạn sẽ cài đặt các tiện ích mở rộng của Google Chrome từ các tệp cục bộ
Trước khi triển khai tiện ích mở rộng của Google Chrome trong Brython, trước tiên bạn sẽ triển khai phiên bản JavaScript rồi dịch phiên bản đó sang Brython
Xin chào thế giới mở rộng trong JS
Khi mới bắt đầu, bạn sẽ triển khai tiện ích mở rộng sẽ thực hiện các tác vụ sau
- Mở cửa sổ bật lên khi bạn nhấp vào biểu tượng tiện ích mở rộng
- Mở thông báo nhắc khi bạn nhấp vào nút cửa sổ bật lên
- Nối thông báo bạn đã nhập ở cuối cửa sổ bật lên ban đầu
Ảnh chụp màn hình sau đây minh họa hành vi này
Trong một thư mục trống, hãy tạo tệp
{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
98 để định cấu hình tiện ích mở rộngimport this
3Trường quan trọng cho ví dụ này là tệp bật lên mặc định,
{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
99, mà bạn cũng sẽ phải tạo. Để biết thông tin về các trường khác và hơn thế nữa, bạn có thể tham khảo tài liệu về định dạng tệp ManifestTrong cùng một thư mục, tạo tệp
{
"count": 1,
"entries": [
{
"API": "Open Government, USA",
"Description": "United States Government Open Data",
"Auth": "",
"HTTPS": true,
"Cors": "unknown",
"Link": "//www.data.gov/",
"Category": "Government"
}
]
}
99 được sử dụng để xác định giao diện người dùng của tiện ích mở rộngimport this
4Tệp HTML bao gồm một liên kết đến logic nghiệp vụ JavaScript của tiện ích mở rộng và mô tả giao diện người dùng của nó
- Dòng 5 đề cập đến
01, chứa logic của phần mở rộng>>> import uuid
- Dòng 8 định nghĩa một
04 sẽ được liên kết với một trình xử lý trong{"code":"fr","hello":"Salut"}
01>>> import uuid
- Dòng 9 khai báo một trường được mã JavaScript sử dụng để hiển thị một số văn bản
Bạn cũng cần tạo
>>> import uuid
01import this
5Logic chính của mã JavaScript bao gồm việc khai báo một trình xử lý
{"code":"fr","hello":"Salut"}
22 được liên kết với trường >>> import uuid
06 của bộ chứa HTML- Dòng 2 gọi chế độ tập lệnh cho phép xác thực nghiêm ngặt hơn trong JavaScript để tiết lộ các lỗi JavaScript
- Dòng 4 chọn trường được xác định bởi
06 trong>>> import uuid
99 và gán nó cho một biến{ "count": 1, "entries": [ { "API": "Open Government, USA", "Description": "United States Government Open Data", "Auth": "", "HTTPS": true, "Cors": "unknown", "Link": "//www.data.gov/", "Category": "Government" } ] }
- Dòng 6 xác định trình xử lý sẽ xử lý sự kiện khi người dùng nhấp vào nút. Trình xử lý sự kiện này nhắc người dùng nhập tên của họ, sau đó thay đổi nội dung của
09 được xác định bằng>>> import uuid
10 thành tên được cung cấp>>> import uuid
Trước khi cài đặt tiện ích mở rộng này, hãy thực hiện các bước sau
- Mở trình đơn Google Chrome ở bên phải màn hình
- Mở menu con Công cụ khác
- Nhấp vào Tiện ích mở rộng
Một màn hình sẽ hiển thị các tiện ích mở rộng hiện được cài đặt của bạn, nếu có. Nó có thể trông như thế này
Để cài đặt tiện ích mở rộng mới, bạn cần thực hiện các bước sau
- Đảm bảo rằng chế độ Nhà phát triển được bật ở phía trên bên phải màn hình
- Nhấp vào Tải đã giải nén
- Chọn thư mục chứa tất cả các tệp bạn vừa tạo
Nếu không có lỗi xảy ra trong quá trình cài đặt, thì bây giờ bạn sẽ thấy một biểu tượng mới có chữ J ở phía bên tay phải của thanh địa chỉ trình duyệt của bạn. Để kiểm tra tiện ích mở rộng của bạn, hãy nhấp vào biểu tượng J của thanh công cụ được hiển thị bên dưới
Nếu có bất kỳ lỗi nào xảy ra trong quá trình cài đặt hoặc thực thi, thì bạn sẽ thấy nút báo lỗi màu đỏ ở bên phải nút Xóa của thẻ mở rộng
Bạn có thể nhấp vào Lỗi để hiển thị lỗi và xác định nguyên nhân gốc rễ. Sau khi sửa, hãy tải lại tiện ích mở rộng bằng cách nhấp vào mũi tên hình tròn ở dưới cùng bên phải của thẻ tiện ích mở rộng, sau đó lặp lại quy trình cho đến khi tiện ích hoạt động như bạn mong đợi
Để kiểm tra tiện ích mở rộng mới cài đặt của bạn, bạn có thể nhấp vào biểu tượng J hiển thị ở phía bên tay phải của thanh công cụ trình duyệt. Nếu biểu tượng không hiển thị, hãy nhấp vào Tiện ích mở rộng để liệt kê các tiện ích mở rộng đã cài đặt và chọn nút đinh ghim được căn chỉnh với tiện ích mở rộng JS Hello World mà bạn vừa cài đặt
Xin chào thế giới mở rộng trong Python
Nếu bạn đã đạt đến điểm này, thì bạn đã hoàn thành các bước khó khăn nhất, chủ yếu là để làm quen với quá trình tạo và cài đặt tiện ích mở rộng của Chrome. Các bước sẽ tương tự với Brython, với một vài điểm khác biệt mà bạn sẽ tìm hiểu trong phần này
Tệp kê khai sẽ khác biệt, với một tên mở rộng khác và để đo lường tốt, một mô tả khác
import this
6Lưu ý rằng bạn cũng phải bao gồm một tài sản mới,
>>> import uuid
11. Điều này là cần thiết để có thể thư giãn trong hệ thống tiện ích mở rộng chrome. Nhớ lấyĐây không phải là thứ bạn đã giới thiệu và bạn có thể kiểm soát ở Brython. Bạn sẽ cần kích hoạt bằng cách sử dụng
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
91 nếu bạn muốn sử dụng Brython làm ngôn ngữ cho tiện ích mở rộng trình duyệt của mình. Nếu bạn không thêm >>> import uuid
15 vào >>> import uuid
11 thì bạn sẽ thấy lỗi sauimport this
7The HTML file will also have a few updates, as follows
import this
8Mã HTML rất giống với mã bạn đã sử dụng để tạo tiện ích mở rộng của Chrome bằng JavaScript. Một vài chi tiết đáng chú ý
- Dòng 5 tải
70 từ gói cục bộ. Vì lý do bảo mật, được tải và bạn không thể tải từ nguồn bên ngoài như CDN1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
- Dòng 6 tải
18, gọi ra>>> import uuid
021from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
- Dòng 7 tải
20>>> import uuid
- Dòng 9 tuyên bố
28 mà không có thông thường1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6ajax.get["//api.publicapis.org/random", 7 blocking=True, 8 oncomplete=on_complete]
22>>> import uuid
Một ràng buộc bảo mật khác ngăn cản bạn gọi
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
02 trong trường hợp >>> import uuid
24 của thẻ 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6ajax.get["//api.publicapis.org/random",
7 blocking=True,
8 oncomplete=on_complete]
28. Giải pháp thay thế là thêm một trình nghe vào tài liệu và chỉ báo cho trình duyệt thực thi 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
02 sau khi nội dung của tài liệu được tảiimport this
9Cuối cùng, bạn có thể thấy logic chính của ứng dụng này trong đoạn mã Python sau
import antigravity
0Cùng với đó, bạn đã sẵn sàng tiến hành cài đặt và thử nghiệm như bạn đã làm đối với tiện ích mở rộng JavaScript chrome
Kiểm tra và gỡ lỗi Brython
Hiện tại không có thư viện thuận tiện để kiểm tra đơn vị mã Brython. Khi Brython phát triển, bạn sẽ thấy nhiều tùy chọn hơn để kiểm tra và gỡ lỗi mã Python trong trình duyệt. Có thể tận dụng khung kiểm tra đơn vị Python cho một mô-đun Python độc lập có thể được sử dụng bên ngoài trình duyệt. Trong trình duyệt, Selenium với trình điều khiển trình duyệt là một lựa chọn tốt. Gỡ lỗi cũng bị hạn chế nhưng có thể
Bài kiểm tra đơn vị Python
Các khung kiểm tra đơn vị Python, chẳng hạn như
>>> import uuid
27 và >>> import uuid
28 tích hợp sẵn, không hoạt động trong trình duyệt. Bạn có thể sử dụng các khung này cho các mô-đun Python cũng có thể được thực thi trong ngữ cảnh của CPython. Không thể kiểm tra bất kỳ mô-đun nào dành riêng cho Brython như 1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
05 bằng các công cụ như vậy tại dòng lệnh. Để biết thêm thông tin về kiểm tra đơn vị Python, hãy xem Bắt đầu với kiểm tra bằng Pythonselen
Selenium là một framework để tự động hóa các trình duyệt. Nó không liên quan đến ngôn ngữ được sử dụng trong trình duyệt, cho dù đó là JavaScript, Elm, Wasm hay Brython, bởi vì nó sử dụng khái niệm WebDriver để hoạt động giống như người dùng tương tác với trình duyệt. Bạn có thể xem Tự động hóa web hiện đại với Python và Selenium để biết thêm thông tin về khung này
Kiểm tra đơn vị JavaScript
Có nhiều khung thử nghiệm tập trung vào JavaScript, như Mocha, Jasmine và QUnit, hoạt động tốt trong hệ sinh thái JavaScript đầy đủ. Nhưng chúng không nhất thiết phải phù hợp để kiểm tra đơn vị mã Python chạy trong trình duyệt. Một tùy chọn yêu cầu hiển thị toàn cầu các hàm Brython cho JavaScript, điều này đi ngược lại các phương pháp hay nhất
Để minh họa tùy chọn hiển thị hàm Brython cho JavaScript, bạn sẽ sử dụng QUnit, bộ kiểm tra đơn vị JavaScript có thể chạy độc lập trong tệp HTML
import antigravity
1Trong một tệp HTML, bạn đã viết mã Python, mã JavaScript và kiểm tra JavaScript để xác thực các chức năng từ cả hai ngôn ngữ được thực thi trong trình duyệt
- Dòng 11 nhập khung QUnit
- Dòng 23 hiển thị
30 cho JavaScript>>> import uuid
- Dòng 28 định nghĩa
31 để kiểm tra hàm JavaScript>>> import uuid
32>>> import uuid
- Dòng 34 định nghĩa
33 để kiểm tra hàm Python>>> import uuid
30>>> import uuid
- Dòng 40 định nghĩa
35 để kiểm tra hàm Python>>> import uuid
30 có lỗi>>> import uuid
Bạn không cần khởi động máy chủ web để thực hiện bài kiểm tra đơn vị. Mở
1from browser import ajax
2
3def on_complete[req]:
4 print[req.text]
5
6language = "fr"
7
8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}",
9 blocking=True,
10 oncomplete=on_complete]
08 trong trình duyệt và bạn sẽ thấy như sauTrang hiển thị hai bài kiểm tra thành công,
>>> import uuid
38 và >>> import uuid
39, và một bài kiểm tra không đạt, >>> import uuid
40Việc hiển thị hàm Python với JavaScript cho thấy cách bạn có thể sử dụng khung kiểm tra đơn vị JavaScript để thực thi Python trong trình duyệt. Mặc dù có thể thử nghiệm, nhưng nói chung, nó không được khuyến nghị vì nó có thể xung đột với các tên JavaScript hiện có
Gỡ lỗi trong Brython
Khi viết bài này, không có công cụ thân thiện với người dùng nào để gỡ lỗi ứng dụng Brython của bạn. Bạn không thể tạo tệp bản đồ nguồn cho phép bạn gỡ lỗi từng bước trong các công cụ phát triển trình duyệt
Điều này không làm bạn nản lòng khi sử dụng Brython. Dưới đây là một số mẹo giúp gỡ lỗi và khắc phục sự cố mã Brython của bạn
- Sử dụng
41 hoặc>>> import uuid
42 để in các giá trị biến trong bảng điều khiển công cụ dành cho nhà phát triển của trình duyệt>>> import uuid
- Sử dụng gỡ lỗi chuỗi f như được mô tả trong Các tính năng mới thú vị trong Python 3. 8
- Thỉnh thoảng xóa IndexedDB của trình duyệt bằng cách sử dụng các công cụ dành cho nhà phát triển
- Vô hiệu hóa bộ đệm của trình duyệt trong quá trình phát triển bằng cách chọn hộp kiểm Tắt bộ đệm trong tab Mạng của công cụ dành cho nhà phát triển của trình duyệt
- Add options to
02 to enable additional debug information to be displayed in the JavaScript console1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
- Sao chép
01 và1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
88 cục bộ để tăng tốc độ tải lại trong quá trình phát triển1from browser import ajax 2 3def on_complete[req]: 4 print[req.text] 5 6language = "fr" 7 8ajax.get[f"//fourtonfish.com/hellosalut/?lang={language}", 9 blocking=True, 10 oncomplete=on_complete]
- Khởi động máy chủ cục bộ khi bạn
36 Mã Python{"code":"fr","hello":"Salut"}
- Mở trình kiểm tra từ tiện ích mở rộng khi khắc phục sự cố tiện ích mở rộng của Chrome
Một trong những điểm hay của Python là REPL [vòng lặp đọc-eval-in]. Bảng điều khiển Brython trực tuyến cung cấp một nền tảng để thử nghiệm, kiểm tra và gỡ lỗi hành vi của một số đoạn mã
Khám phá các lựa chọn thay thế cho Brython
Brython không phải là lựa chọn duy nhất để viết mã Python trong trình duyệt. Một vài lựa chọn thay thế có sẵn
- điêu khắc
- chuyển mã
- pyodua
- PyPy. js
Mỗi triển khai tiếp cận vấn đề từ một góc độ khác nhau. Brython cố gắng thay thế JavaScript bằng cách cung cấp quyền truy cập vào cùng một API web và thao tác DOM như JavaScript, nhưng với sự hấp dẫn của cú pháp và thành ngữ Python. Nó được đóng gói dưới dạng một bản tải xuống nhỏ so với một số lựa chọn thay thế có thể có các mục tiêu khác nhau
Ghi chú. Tại PyCon US 2022, một giải pháp thay thế mới đã được công bố. PyScript. Để có hướng dẫn về khung mới này, bạn có thể xem Cái nhìn đầu tiên về PyScript. Python trong Trình duyệt web
Làm thế nào để các khuôn khổ so sánh?
điêu khắc
Skulpt biên dịch mã Python thành JavaScript trong trình duyệt. Quá trình biên dịch diễn ra sau khi trang được tải, trong khi ở Brython, quá trình biên dịch diễn ra trong khi tải trang
Mặc dù không có chức năng tích hợp để thao tác DOM, Skulpt rất gần với Brython trong các ứng dụng của nó. Điều này bao gồm việc sử dụng giáo dục và các ứng dụng Python toàn diện, như Anvil đã minh họa
Skulpt là một dự án được duy trì hướng tới Python 3. Brython gần như ngang bằng với Python 3. 9 cho các mô-đun tương thích với việc thực thi trong trình duyệt
chuyển mã
Transcrypt bao gồm một công cụ dòng lệnh để biên dịch mã Python thành mã JavaScript. Quá trình biên dịch được cho là đi trước thời hạn [AOT]. Mã kết quả sau đó có thể được tải vào trình duyệt. Transcrypt có dung lượng nhỏ, khoảng 100KB. Nó nhanh và hỗ trợ thao tác DOM
Sự khác biệt giữa Skulpt và Brython là Transcrypt được biên dịch sang JavaScript bằng trình biên dịch Transcrypt trước khi được tải xuống và sử dụng trong trình duyệt. Điều này cho phép tốc độ và kích thước nhỏ. Tuy nhiên, nó ngăn không cho Transcrypt được sử dụng làm nền tảng cho giáo dục như các nền tảng khác
pyodua
Pyodide là một phần tổng hợp WebAssugging của trình thông dịch CPython. Nó diễn giải mã Python trong trình duyệt. Không có giai đoạn biên dịch JavaScript. Mặc dù Pyodide, như PyPy. js, yêu cầu bạn tải xuống một lượng dữ liệu đáng kể, nó được tải với các thư viện khoa học như NumPy, Pandas, Matplotlib, v.v.
Bạn có thể thấy Pyodide là môi trường Jupyter Notebook chạy hoàn toàn trong trình duyệt chứ không phải được phục vụ bởi máy chủ phụ trợ. Bạn có thể thử nghiệm với Pyodide bằng ví dụ trực tiếp
PyPy. js
PyPy. js sử dụng trình thông dịch PyPy Python được biên dịch sang JavaScript bằng emscripten, làm cho nó tương thích để chạy trong trình duyệt
Ngoài trạng thái không hoạt động hiện tại của dự án, PyPy. js là một gói lớn, khoảng 10 MB, không phù hợp với các ứng dụng web thông thường. Bạn vẫn có thể sử dụng PyPy. js làm nền tảng để học Python trong trình duyệt bằng cách mở PyPy. trang chủ js
PyPy. js được biên dịch thành JavaScript với emscripten. Pyodide tiến thêm một bước, tận dụng đặc biệt là emscripten và Wasm để biên dịch các phần mở rộng Python C như NumPy thành WebAssugging
Khi viết bài này, PyPy. js dường như không được duy trì. For something in the same vein regarding the compilation process, consider Pyodide
Phần kết luận
Trong hướng dẫn này, bạn đã tìm hiểu sâu về một số khía cạnh của việc viết mã Python trong trình duyệt. Điều này có thể khiến bạn quan tâm đến việc dùng thử Python để phát triển giao diện người dùng
Trong hướng dẫn này, bạn đã học cách
- Cài đặt và sử dụng Brython trong môi trường cục bộ
- Thay thế JavaScript bằng Python trong các ứng dụng web mặt trước của bạn
- Thao tác DOM
- Tương tác với JavaScript
- Tạo tiện ích mở rộng trình duyệt
- So sánh các lựa chọn thay thế với Brython
Ngoài việc truy cập các tính năng thường dành riêng cho JavaScript, một trong những ứng dụng tốt nhất của Brython là công cụ học tập và giảng dạy. Bạn có thể truy cập trình chỉnh sửa Python và bảng điều khiển chạy trong trình duyệt của mình để bắt đầu khám phá nhiều cách sử dụng Brython ngay hôm nay
Để xem lại các ví dụ bạn đã thấy trong hướng dẫn này, bạn có thể tải xuống mã nguồn bằng cách nhấp vào liên kết bên dưới
Get the Source Code. Click here to get the source code you’ll use to learn about using Brython to run Python in the browser in this tutorial
Đánh dấu là đã hoàn thành
🐍 Thủ thuật Python 💌
Nhận một Thủ thuật Python ngắn và hấp dẫn được gửi đến hộp thư đến của bạn vài ngày một lần. Không có thư rác bao giờ. Hủy đăng ký bất cứ lúc nào. Được quản lý bởi nhóm Real Python
Gửi cho tôi thủ thuật Python »
Giới thiệu về André Burgaud
Andre là một kỹ sư phần mềm dày dặn đam mê công nghệ và ngôn ngữ lập trình, đặc biệt là Python
» More about AndreEach tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are
Aldren
David
Jon
Joanna
Gia-cốp
Master Real-World Python Skills With Unlimited Access to Real Python
Tham gia với chúng tôi và có quyền truy cập vào hàng nghìn hướng dẫn, khóa học video thực hành và cộng đồng các Pythonistas chuyên gia
Level Up Your Python Skills »
Master Real-World Python Skills
With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas
Level Up Your Python Skills »
What Do You Think?
Đánh giá bài viết này
Tweet Share Share EmailWhat’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know
Commenting Tips. The most useful comments are those written with the goal of learning from or helping out other students. and get answers to common questions in our support portal