1673466117
What to Expect in Web Development and JavaScript in 2023
What makes web development so appealing to more and more people every year? One of the reasons is the constant evolution of existing web technologies and the emergence of new ones, which allow many to find their path in the IT industry.
Even though we are very busy with improving and diversifying DHTMLX offerings for web developers, we still find time to follow the main trends and novelties on the web landscape, and in JavaScript in particular. Similar to the previous years, we are ready to share with you the most interesting findings from turbulent 2022 and make forecasts for 2023. Moreover, you will also learn about the principal achievements of the DHTMLX team over the last twelve months and our plans for the future.
#JavaScript #web-development #CSS #security #trends #frameworks #typescript #GitHub
Programming Languages: JavaScript Maintains Leadership but TypeScript is Not Far Away
It is rightly said that the only constant in web development is changing, but for many years this rule does not apply to the ranking of the most popular programming languages. JavaScript continues to be the King of the web. According to the latest Redmonk’s analysis, JavaScript leads the popularity race, leaving behind strong competitors such as Python, Java, and gradually rising TypeScript.
But despite its widespread use, it is hard to call JavaScript the most loved and desirable programming language. The state of things based on these important criteria is clearly shown in the Stack Overflow Developer Survey 2022.
TypeScript has been around for a decade, developing from one more controversial coding technology into a true salvation for many web developers. TypeScript brought significant improvements to the developer experience and helped mitigate numerous shortcomings of JavaScript.
Microsoft publicly supported a proposal to bring the type syntax from TypeScript to JavaScript back in March 2022. It is too early to say whether this idea will work out or not, but many developers miss this feature in JavaScript.
The State of Frontend 2022 survey includes the question on the prospects of TypeScript addressed to 3703 frontend professionals from 125 countries, and you can see from the results below that the trust of the dev community in TypeScript is growing.
The majority of respondents (43%) believe that TypeScript will be a full-fledged replacement for JavaScript or at least will be equally popular (27,6%) and there is little faith that it will be forgotten any time soon (1%). We also share this optimism about the potential of TypeScript and it is one of the reasons why DHTMLX products support TypeScript. And there are all prerequisites to assume that TypeScript will continue chasing JavaScript in 2023.
JavaScript Frameworks: Shifting in Traditional Balance of Power
The State of Frontend 2022 survey will also help us analyze changes taking place in the area of frontend frameworks. In recent years, it has become less surprising to see that the common “Big Three” (i.e. React, Angular, Vue) is slowly taking new forms.
Participants of the survey most often preferred React (76,2%), Next.js (43,1), and Vue (28,9%) for their projects in 2022. If the presence of React and Vue raises no questions, some of you may wonder what’s so special about Next.js?
Next.js works on top of React, and these frameworks may seem quite similar. Next.js significantly improves some essential React features and adds new ones. But the main distinguishing trait of Next.js is the ability to use server-side rendering (SSR) and static site generation (SSG) techniques in the same app.
No wonder Next.js is also presented in the list of frameworks that the respondents want to learn in the future. In this category, it goes 3rd (33,5%) right after already loved by many Svelte (49,2%) and another promising React-based framework named Remix (36,2%).
We can assume that React, which is expected to adopt server components as a stable feature in one of the upcoming updates, and React-based frameworks will continue to be popular choices among web developers in 2023.
Bun: New Name in JavaScript Ecosystem or Another Temporary Thing
In 2022, the web development community first heard about the new ambitious project named Bun. It is a new JavaScript runtime environment designed by the company Oven to become a worthy alternative to Node.js and Deno.
Bun is promoted as an all-in-one tool equipped with a native bundler, transpiler, task runner, and npm client. But the key peculiarity of the new runtime is said to be an exceptional performance. And when you take a look at the benchmarks provided by the Bun development team, the numbers seem truly impressive.
So what makes Bun so fast? There are two primary reasons for this:
Although Bun is called experimental software even by its creators and is currently available in a public beta version, it has sparked great interest among developers. The GitHub repository of the project has already received 37k stars!
It is hard to say for sure whether Bun will be a success or end in nothing, but we should certainly keep an eye on this intriguing project in 2023.
Container Technologies Become Indispensable for Developers
Today, many web developers can hardly imagine their work without containers. Container technologies (or simply containers) are software units that serve for packaging the code of your app together with all dependencies into a single package so it can run in any environment. The most popular examples of this technology are Docker and Kubernetes, which have been around for more than a decade. It is noteworthy that the respondents of the Developer Survey 2022 named Docker and Kubernetes the most loved and wanted tools.
Here comes a logical question: why are developers so eager to use containers in their projects? The statistics provided by Statista show the list of the main benefits of container technology in 2022.
In general, container technologies enable developers to build and deploy apps faster and more securely, thus containers will hardly lose relevance in 2023.
1669109040
As Machine Learning models are intricate, several efficient Machine Learning frameworks are implemented to reduce the complexity and aid developers to quickly optimize and comeup with models without the headache of the granular details of underlying algorithms.
Let us go over the interfaces, libraries, and tools that are indispensable to the domain of Machine Learning. Here is the list of topics that this blog will cover along with the top 15 Machine Learning Frameworks:
In its true sense, a Machine Learning framework is a collection of pre-built components that support the process of building Machine Learning models in a more efficient and optimized manner. It uses traditional methods and is very convenient for developers to use. As far as the computation process is concerned, these frameworks provide for parallelization. Good Machine Learning frameworks tackle the complexity of Machine Learning to make it more convenient and available for developers.
Today, we will take a look at the top 15 Machine Learning tools and frameworks that you can use to make ML modeling easier.
Amazon Machine Learning is a cloud-based service that consists of visualization tools for developers at all skill levels. For predictions, Amazon ML uses simple APIs in applications; there is no need for custom code or any kind of infrastructure management for this. Amazon ML can run multiclass categorization, binary classification, or regression on the data stored in Amazon S3, Amazon Redshift, or RDS to create a model. There is no need for complex algorithms with Amazon ML.
Amazon ML can:
Apache SINGA is a distributed Deep Learning platform that was developed by the NUS Big Data Systems team. It comprises an open-source ML library with a scalable architecture that can run over a wide range of hardware; due to its capability to support a number of Deep Learning models, SINGA allows users to customize the models. The programming model is quite simple and that makes the distributed training process transparent to the users.
Training a Deep Learning model or submitting a job in SINGA requires users to configure the job with their own built-in layer, updater, etc., which is not the case in Hadoop.
Take up Apache Spark Certification and learn from the best at Intellipaat!
TensorFlow is an open-source library, developed by Google Brain, that uses data flow graphs during numerical operations and performances. It comes with a rich set of tools and requires a sound knowledge of NumPy arrays. Batches of data called tensors are processed by a series of algorithms described by a graph that can be assembled with Python or C++. TensorFlow can run on both CPUs and GPUs.
TensorFlow is one of the most common Machine Learning frameworks. While it is simple enough to generate a prediction on a given data set, it can also handle multiple data pipelines, customization of all layers and parameters of a model, data transformations to fit the model, training multiple machines without compromising user privacy, etc.
Intellipaat’s Artificial Intelligence Course will help you to learn everything about Deep Learning and TensorFlow.
scikit-learn is a free ML library and is a Python Machine Learning framework. It is designed to leverage Python’s numerical and scientific libraries, namely, NumPy, SciPy, and Matplotlib. scikit-learn is open source, reusable, and has tools for several ML tasks such as:
scikit-learn can also assess the performance of a model with the help of tools such as the confusion matrix. From scikit-learn, users can always move to other frameworks seamlessly.
MLlib Spark is the ML library by Apache Spark that includes common learning algorithms and utilities along with the following:
As is the case with most ML frameworks, it aims to make practical Machine Learning convenient and scalable. MLlib has APIs in Java, Python, R, and Scala.
Register today for the Python Course by Intellipaat.
Torch has a fast-scripting language and is very efficient. It aims to feature maximum flexibility, simplicity, and speed while users build scientific algorithms. It supports ML algorithms that prioritize GPUs and has an underlying C/CUDA implementation and LuaJIT.
Torch includes community-driven packages in Machine Learning, parallel processing, signal processing, computer vision, image, audio, video, networking, and much more.
PyTorch was developed by FAIR, Facebook AI Research. In early 2018, the FAIR team merged Caffe2, another ML framework, into PyTorch. It is the leading competitor to TensorFlow. Engineers are often in a dilemma whether to use Tensorflow or PyTorch.. Although, they each serve their purposes but are pretty interchangeable.
Like TensorFlow, PyTorch does regression, classification, neural networks, etc. and runs on both CPUs and GPUs.
PyTorch is considered more pythonic. Where TensorFlow can get a model up and running faster and with some customization, PyTorch is considered more customizable, following a more traditional object-oriented programming approach through building classes.
PyTorch is shown to have faster training times. This speed is marginal for many users but can make a difference on large projects. PyTorch and TensorFlow are both in active development, so the speed comparison is likely to waiver back and forth between the two.
Relative to Torch, PyTorch uses Python and has no need for Lua or the Lua Package Manager.
The Shogun Machine Learning Toolbox is devoted to making machine learning tools available for free, to everyone. It provides efficient implementation of all standard ML algorithms. Shogun ensures that the underlying algorithms are transparent and accessible—a unified interface provides access via many popular programming languages, including C++, Python, Octave, R, Java, Lua, C#, and Ruby.
Spark ML can handle large matrix multiplications. This is possible because it runs in clusters and the calculations are done on different servers. Matrix multiplications require a distributed architecture for optimized speed and reduced memory issues while handling large data sets.
It is possible to use Spark ML with Spark SQL DataFrames, which is quite familiar to most Python programmers. Spark ML allows working with Spark RDD data structure instead of NumPy arrays. This eliminates some complexity from data preparation for ML algorithms as it creates Spark feature vectors.
Keeping speed, modularity, and articulation in mind, Berkeley Vision and Learning Center (BVLC) and community contributors came up with Caffe, a Deep Learning framework. Its speed makes it ideal for research experiments and production edge deployment. It comes with a BSD-authorized C++ library with a Python interface, and users can switch between CPU and GPU. Google’s DeepDream implements Caffe. However, Caffe is observed to have a steep learning curve, and it is also difficult to implement new layers with Caffe.
H2O is another open-source Machine Learning framework. It is business-oriented and implements predictive analytics and math to help drive decisions based on data and insights. This AI tool brings together unique features such as database-agnostic support for all common database and file types, easy-to-use WebUI and familiar interfaces, and the best open-source Breed technology. H2O comes with several models and includes Python, R, Java, JSON, Scala, JavaScript, and a web interface. H2O’s core code is in Java, and the REST API allows access from any external program or script to H2O’s capabilities. It allows users to work with existing languages and AI tools extend into Hadoop environments without any issues. H2O can be used in predictive modeling, advertising technology, healthcare, customer intelligence, risk and fraud analysis, insurance analytics, etc.
Prepare yourself for the industry by going through Top Machine Learning Interview Questions and Answers now!
Keras is built on top of TensorFlow but is not limited to it. This makes modeling simple and straightforward. This neural network library can use the same code to run both on CPU and GPU. Some of the coding processes can be simplified with Keras.
Keras can be used with:
Check out this video tutorial on Keras and TensorFlow by Intellipaat:
mlpack, an ML framework, is based on C++ and is specifically designed to optimize speed, scalability, and use. There are 16 available repositories, and the implementation of this ML library can be carried out with command-line executables for novice users or with the C++ API for high performance and flexibility. The algorithms provided by this framework can be later integrated into large-scale solutions.
By using C++ templates, users can avoid copying data sets; the templates work on expression optimizations that are not available in other languages.
Azure users can build and train models by using these Machine Learning frameworks. These models can be turned into APIs for use by other services. There is 10 GB of storage per account for model data. However, any Azure storage can be connected to larger models.
Thanks to Microsoft and third parties, Azure ML Studio comes with a wide range of algorithms. There is no need for an account to try them out. You will get up to eight hours of anonymous login.
Check out this Azure Certification to learn about different certifications in Azure.
Google Cloud ML Engine aids data scientists and developers to build and run superior ML models. It uses Google’s distributed network of computers. Google speeds up the process by running the algorithm on multiple computers. Cloud ML Engine’s prediction and training services can be used separately as well as together. Its applications come in the form of solutions for food safety, quick customer emails, the presence of clouds in satellite images, etc.
Another benefit is that with Cloud ML Engine, the training data can be easily stored online in buckets in Google Cloud Storage.
Earning a Google Cloud Certification is easy with Intellipaat. Register today!
Theano was developed at the LISA lab and was released under a BSD license as a Python library that rivals the speed of the hand-crafted implementations of C. Theano is especially good with multidimensional arrays and lets users optimize mathematical performances, mostly in Deep Learning with efficient Machine Learning Algorithms. Theano uses GPUs and carries out symbolic differentiation efficiently.
Several popular packages, such as Keras and TensorFlow, are based on Theano. Unfortunately, Theano is now effectively discontinued but is still considered a good resource in ML.
Veles is written in C++ and has its applications in Deep Learning. Veles is a distributed platform that implements Python for node automation and coordination. Veles’s main focus is on flexibility and performance. By using Veles, one can analyze data sets and automatically normalize them before feeding them into the cluster. A REST API makes the trained model ready to be used for production immediately. Veles enables the training of convolutional nets, recurrent nets, fully connected nets, and many more popular topologies.
Before choosing from these Machine Learning frameworks, turn your attention to the goal at hand, Machine Learning or Deep Learning.
Deep Learning requires neural networks to analyze a range of data through several tasks. The data could be:
Machine Learning relies on mathematical and statistics-based algorithms to find patterns. Keeping that in mind, you can look up tools that enable solutions such as regression, k-mean clustering, neural networks, etc.
For choosing suitable ML frameworks, here are some of the best practices that are followed across the industry:
Enroll in this Machine Learning Course by Intellipaat and become an expert.
The frameworks and tools listed in this blog not only democratize the algorithm development but also accelerate and simplify the process. In addition to the ML frameworks in the open source community, some of the large enterprises today, have also built their own frameworks for their in-house operations.
Original article source at: https://intellipaat.com/
1666356824
In this article, we'll discuss the most popular frontend frameworks and how to choose the best one for your project. We'll go over the different features and benefits of each framework, and help you decide which one is right for you.
So if you're looking to improve your web development skills, this article is for you.
https://www.zupyak.com/p/3322704/t/the-most-used-front-end-frameworks-for-web-development
1663899489
In today's post we will learn about 8 Popular Web Servers Libraries for Rust.
What is Web Servers?
A web server is computer software and underlying hardware that accepts requests via HTTP (the network protocol created to distribute web content) or its secure variant HTTPS. A user agent, commonly a web browser or web crawler, initiates communication by making a request for a web page or other resource using HTTP, and the server responds with the content of that resource or an error message. A web server can also accept and store resources sent from the user agent if configured to do so.
Table of contents:
A blazing fast and asynchronous web server for static files-serving. ⚡
Static Web Server (or SWS
abbreviated) is a very small and fast production-ready web server suitable to serve static web files or assets.
It is focused on lightness and easy-to-use principles while keeping high performance and safety powered by The Rust Programming Language.
Written on top of Hyper and Tokio runtime. It provides concurrent and asynchronous networking abilities as well as the latest HTTP/1 - HTTP/2 implementations.
It's cross-platform and available for Linux
, macOS
, Windows
and FreeBSD
(x86
/x86_64
, ARM
/ARM64
) as well as Docker
.
x86
,x86_64
,ARM
,ARM64
).For more details about the API, usage and examples please have a look at The Documentation Website.
v1
please go to 1.x branch.v1
to v2
please take a look at Migrating from v1
to v2
release.A blazingly fast static web server with routing, templating, and security in a single binary you can set up with zero code.
A fast static web server with TLS (HTTPS), Routing, Hot Reloading, Caching, Templating, and Security in a single-binary you can set up with zero code.
Built from the ground up for self-hosters with performance, ease of use, and portability in mind. ❤️
Features
fast_mem_cache
enabled) and serving static files from memory. On the client-side, Cache-Control
, Etag
, and Last-Modified
are utilized.Download the executable for your OS from Releases, then just run it:
mkdir mywebsite/
binserve
On the first run, it will create the configuration file and a starter boilerplate for you to get started.
_ _
| |_|_|___ ___ ___ ___ _ _ ___
| . | | |_ -| -_| _| | | -_|
|___|_|_|_|___|___|_| \_/|___| 0.2.0
[INFO] Build finished in 295 μs ⚡
[SUCCESS] Your server is up and running at 127.0.0.1:1337 🚀
Go to http://127.0.0.0:1337/ and you will be greeted with the index page of Binserve.
Now all you need to do is to edit the binserve.json
file. (See Configuration).
Download the executable from Releases OR Install with cargo
:
cargo install --git https://github.com/mufeedvh/binserve.git
Prerequisites:
git clone https://github.com/mufeedvh/binserve.git
cd binserve/
RUSTFLAGS="-C target-cpu=native" cargo build --release
The first command clones this repository into your local machine and the last two commands enters the directory and builds the source in release mode.
A minimal file upload/pastebin service.
Rustypaste is a minimal file upload/pastebin service.
$ echo "some text" > awesome.txt
$ curl -F "file=@awesome.txt" https://paste.site.com
https://paste.site.com/safe-toad.txt
$ curl https://paste.site.com/safe-toad.txt
some text
capital-mosquito.txt
)yB84D2Dv.txt
)cargo install rustypaste
pacman -S rustypaste
See the available binaries on releases page.
git clone https://github.com/orhun/rustypaste.git
cd rustypaste/
cargo build --release
# run unit tests
cargo test -- --test-threads 1
The standalone command line tool (rpaste
) is available here.
function rpaste() {
curl -F "file=@$1" -H "Authorization: <auth_token>" "<server_address>"
}
* consider reading authorization headers from a file. (e.g. -H @rpaste_auth
)
# upload a file
$ rpaste x.txt
# paste from stdin
$ rpaste -
$ curl -F "file=@x.txt" -H "expire:10min" "<server_address>"
(supported units: ns
, us
, ms
, sec
, min
, hours
, days
, weeks
, months
, years
)
A demonstration of how a Rust GraphQL server can be used as a remote schema with Hasura.
user
, with a id
column of type uuid
, and also a username
column of type text
.ADMIN_SECRET
and a JWT_SECRET
on the graphql engine, and share these with the Rust server as environment variables.schema.json
gq $HASURA_ENDPOINT -H "x-hasura-admin-secret: $ADMIN_SECRET" --introspect --format json > ./graphql/schema.json
cargo run
Key | Example |
---|---|
PORT | 8000 |
HASURA_ENDPOINT | http://127.0.0.1:8080/v1/graphql |
ADMIN_SECRET | foo |
JWT_SECRET | {"type":"HS256","key":"3QQ6FD+o0+c7tzQQVfjpMkNDi2yARAAKzQQk8O2IKoxQQ4nF7EdAh8s3TwpHwrdQQ6R"} |
A small, self-contained cross-platform CLI tool that allows you to just grab the binary and serve some file(s) via HTTP.
miniserve is a small, self-contained cross-platform CLI tool that allows you to just grab the binary and serve some file(s) via HTTP. Sometimes this is just a more practical and quick way than doing things properly.
miniserve linux-distro-collection/
miniserve linux-distro.iso
miniserve --index test.html
miniserve --spa --index index.html
miniserve --auth joe:123 unreleased-linux-distros/
pw=$(echo -n "123" | sha256sum | cut -f 1 -d ' ')
miniserve --auth joe:sha256:$pw unreleased-linux-distros/
miniserve -i 192.168.0.1 --random-route /tmp
# Serving path /private/tmp at http://192.168.0.1/c789b6
miniserve -i 192.168.0.1 -i 10.13.37.10 -i ::1 /tmp/myshare
miniserve --tls-cert my.cert --tls-key my.key /tmp/myshare
curl
:# in one terminal
miniserve -u .
# in another terminal
curl -F "path=@$FILE" http://localhost:8080/upload\?path\=/
(where $FILE
is the path to the file. This uses miniserve's default port of 8080)
curl
:# in one terminal
miniserve --upload-files --mkdir .
# in another terminal
curl -F "mkdir=$DIR_NAME" http://localhost:8080/upload\?path=\/
(where $DIR_NAME
is the name of the directory. This uses miniserve's default port of 8080.)
miniserve -u -m image -q
This uses the --media-type
option, which sends a hint for the expected media type to the browser. Some mobile browsers like Firefox on Android will offer to open the camera app when seeing this.
Host These Things Please - A basic http server for hosting a folder fast and simply.
If you have cargo
installed (you're a Rust developer) all you need to do is:
cargo install https
Which will install http
and httplz
(identical, disable one or another if they clash) in the folder where all other binaries go.
Available from the community repository as httplz
:
pacman -S httplz
If, however, you're not a Rust developer, but you have sh
-like shell, you can use an installer (works on Windows and Linux):
curl -SsL https://cdn.rawgit.com/thecoshman/http/master/install.sh | sh
# or, if you like taking precautions
sh -c "$(curl -SsL https://cdn.rawgit.com/thecoshman/http/master/install.sh)"
You can change the installation directory by setting the PREFIX
environment variable (default - /usr/bin
):
PREFIX=$HOME/bin curl -SsL https://cdn.rawgit.com/thecoshman/http/master/install.sh | sh
# Windows:
set PREFIX=D:\Akces
curl -SsL https://cdn.rawgit.com/thecoshman/http/master/install.sh | sh
If you're on a Debian-based amd64 machine, you can also grab a .deb
package from the latest release page.
If you're on Windows and prefer a more guided installation (or you don't have a shell), you can download the Windows installer from the latest release's page. (Note: you can add /D INSTALLDIR to installer command line to change the installation directory.)
The idea is to make a program that can compile down to a simple binary that can be used via Linux CLI to quickly take the current directory and serve it over HTTP. Everything should have sensible defaults such that you do not have to pass parameters like what port to use.
It's not going to be a 'production ready' tool, it's a quick and dirty way of hosting a folder, so whilst I'll try to make it secure, it is not going to be a serious goal.
Simple static http server.
Simple HTTP(s) Server 0.6.3
USAGE:
simple-http-server [FLAGS] [OPTIONS] [--] [root]
FLAGS:
--coep Add "Cross-Origin-Embedder-Policy" HTTP header and set it to "require-corp"
--coop Add "Cross-Origin-Opener-Policy" HTTP header and set it to "same-origin"
--cors Enable CORS via the "Access-Control-Allow-Origin" header
-h, --help Prints help information
-i, --index Enable automatic render index page [index.html, index.htm]
--nocache Disable http cache
--norange Disable header::Range support (partial request)
--nosort Disable directory entries sort (by: name, modified, size)
-s, --silent Disable all outputs
-u, --upload Enable upload files (multiple select) (CSRF token required)
-V, --version Prints version information
OPTIONS:
-a, --auth <auth> HTTP Basic Auth (username:password)
--cert <cert> TLS/SSL certificate (pkcs#12 format)
--certpass <certpass> TLS/SSL certificate password
-c, --compress <compress>...
Enable file compression: gzip/deflate
Example: -c=js,d.ts
Note: disabled on partial request!
--ip <ip> IP address to bind [default: 0.0.0.0]
-p, --port <port> Port number [default: 8000]
--redirect <redirect> takes a URL to redirect to using HTTP 301 Moved Permanently
-t, --threads <threads> How many worker threads [default: 3]
--try-file <PATH>
serve this file (server root relative) in place of missing files (useful for single page apps) [aliases:
try-file-404]
-l, --upload-size-limit <upload_size_limit> Upload file size limit [bytes] [default: 8000000]
Installation
# Install Rust
curl https://sh.rustup.rs -sSf | sh
# Install simple-http-server
cargo install simple-http-server
rehash
simple-http-server -h
Features
Static HTTP file server.
Simple and fast web server as a single executable with no extra dependencies required.
HTTP/1
and HTTP/2
supportauto
, gzip
, deflate
or br
Quick start in current directory:
see start
or specify the port and directory via parameters:
see start -b 80 -p /root/www
Also, you can use see -c [FILE]
to specify a configuration file or just use the default one in ~/.see.conf
. Below, a simple configuration example to start the HTTPS server:
server {
listen 80
root /root/www
}
server {
listen 443
root /root/www
host example.com
https {
key ./ssl.key
cert ./ssl.pem
}
}
Download the compiled executable corresponding to your system from the release page.
cargo install see
# or
cargo install --git https://github.com/wyhaya/see
docker pull wyhaya/see
Add the following to see.conf
:
server {
listen 80
echo Hello, world!
}
and run the container:
docker run -idt --name see -p 80:80 -p 443:443 -v '$PWD'/see:/ wyhaya/see
lastly, open the link http://localhost and you should see Hello, world!
.
Thank you for following this article.
Best Rust Backend Web Frameworks
1663854067
In this blog, we take a look at the most popular front-end web development frameworks and languages. We explore what each one is used for and some of their pros and cons. By the end of this video, you'll have a good idea of which framework or language might be best for you to learn.
1663005600
In today's post we will learn about 8 Best Libraries for Node-Powered CMS Frameworks with JavaScript.
Content management systems (CMS) enable people without a strong technical background to publish content. We can use CMSs to manage our content and its delivery. There are different type of CMSs that perform different purposes and come with different features.
In this article, we will learn about some of the best Node.js CMSs, and hopefully can serve as a guide we can use to choose the best CMS that fits our requirements.
Table of contents:
Keystone 6 is published to npm under the @keystone-6/*
namespace.
You can find our extended documentation on our website, but some quick links that might be helpful:
create-keystone-app
CLI.💡 While our
API Reference
is generally complete, we are are still working hard on increasing the fidelity of ourguides
andexamples
. If you have an example you'd like see, please open a GitHub discussion!
Our @keystone-6/*
packages are written for the Node Maintenance and Active LTS versions of Node; and our continuous integration seamlessly tracks that. You may have success with Node versions that are Pending or End-of-Life, but you may have problems too.
The Keystone 5 codebase is now in maintenance mode and lives at keystonejs/keystone-5. For more information read Keystone 5 and beyond.
For a birds-eye view of what the Keystone project is working towards, check out our Roadmap.
Share your thoughts and feature requests on Slack (preferred) or Twitter. Bugfixes and issues always welcome.
For complete documentation go to Open Commerce Quickstart for all supported operating systems.
git clone https://github.com/reactioncommerce/reaction-development-platform.git
cd reaction-development-platform
make
Behind the scenes, the make process clones all of the relevant Open Commerce software repositories, sets up each environment, and pulls, builds, and starts each Docker container.
When make completes, three services will be running on localhost:
Go to the complete installation instructions to see how to set up your store
The easiest way to get a production instance deployed is with our official Ghost(Pro) managed service. It takes about 2 minutes to launch a new site with worldwide CDN, backups, security and maintenance all done for you.
For most people this ends up being the best value option cause of how much time it saves — and 100% of revenue goes to the Ghost Foundation; funding the maintenance and further development of the project itself. So you’ll be supporting open source software and getting a great service!
If you prefer to run on your own infrastructure, we also offer official 1-off installs and managed support and maintenance plans via Ghost(Valet) - which can save a substantial amount of developer time and resources.
If you want to run your own instance of Ghost, in most cases the best way is to use our CLI tool
npm install ghost-cli -g
Then, if installing locally add the local
flag to get up and running in under a minute - Local install docs
ghost install local
or on a server run the full install, including automatic SSL setup using LetsEncrypt - Production install docs
ghost install
Check out our official documentation for more information about our recommended hosting stack & properly upgrading Ghost, plus everything you need to develop your own Ghost themes or work with our API.
For anyone wishing to contribute to Ghost or to hack/customize core files we recommend following our full development setup guides: Contributor guide • Developer setup • Admin App dev guide
ApostropheCMS is content software for everyone in an organization. It helps teams of all sizes create dynamic digital experiences with elegance and efficiency by blending powerful features, developer happiness, and a low learning curve for content creators. Apostrophe has powered websites and web apps for organizations large and small for over a decade.
To get started with Apostrophe 3, follow these steps to set up a local development environment. For more detail, refer to the A3 getting started guide in the documentation.
We recommend installing the following with Homebrew on macOS. If you're on Linux, you should use your package manager (apt or yum). If you're on Windows, we recommend the Windows Subsystem for Linux.
Software | Minimum Version | Notes |
---|---|---|
Node.js | 12.x | Or better |
npm | 6.x | Or better |
MongoDB | 3.6 | Or better |
Imagemagick | Any | Faster image uploads, GIF support (optional) |
By following these steps you will be running your own CMS system in no time. If any of the steps do not work for you, please report this as an issue on this github repository and we will look into it as soon as possible!
Create a new directory for your cms and navigate to it (in unix):
$ mkdir codydev
$ cd codydev
Install cody and its dependencies
$ npm install cody
Set up a new web site using the guided scaffolding
$ node ./node_modules/cody/bin/create_site
Creating cody web tree in current directory
1) Enter sitename: mysite
Note: also using my site as database name.
Note: by default the mysql root user has no password so you can just hit enter, if you forgot the root password see http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html
2) Enter root password for mysql so we can create a new database and user:
3) Enter site database user: mysitename
4) Enter site database password: mysitepassword
5) Enter hostname for site: mysite.local (or localhost)
Site mysite has been prepared.
Please create DNS entries, or add to /etc/hosts:
127.0.0.1 mysite.local
Also check index.js and config.json to fine-tune extra parameters, encryption key, ...
Start your site using:
forever start mysite.js
or
node mysite.js
Add a DNS entry for given hostname, e.g.
$ sudo bash -c 'echo 127.0.0.1 mysite.local >> /etc/hosts'
Run the server
$ node mysite.js
or if you want to automatically restart the server on changes
$ forever start mysite.js
Go to "http://mysite.local:3001" to see your current site and go to "http://mysite.local:3001/en/dashboard" to see the CMS of the site.
the default users are: 'super', 'admin', 'test' and 'user' which all have password 'empty' you can ofcourse use "http://localhost:3001" too.
Hatch.js requires Node 0.8+, Redis 2.6+ and imagemagick to be installed. Bower is also required to install client-side dependencies.
npm install -g bower
Use Hatch.js as an npm. Please see the examples for how to use Hatch.js in this way:
npm install hatchjs
Or standalone:
git clone https://github.com/inventures/hatchjs
Then:
npm install
bower install
Like most node apps, Hatch.js listens by default on port 3000. We recommend using Nginx or similar to proxy requests via port 80 or 443.
node server
Running in production mode is strongly recommended for live sites. Assets are automatically combined, minified and strongly cached, view templates are pre-compiled resulting in better performance all round:
NODE_ENV=production node .
NODE_ENV=production CLUSTER=1 node .
Visit http://hostname:3000 to get started with your first group.
By default Hatch.js connects to Redis DB 0 on 127.0.0.1. You can change this by modifying ./config/database.js
.
Please take a look at the demo installation instance: https://demo.taracot.org/cp (use admin as username and admin as password).
Note: the demo is automatically re-installing every hour.
Follow this guide for TaracotJS instance installation.
Download and install Node.js for your operating system: http://nodejs.org/download/. Node Package Manager (npm) should be installed by default; if not, please take care of it's installation.
MongoDB and Redis are required. If your operating system is x64-based Windows, you may download the pre-compiled MongoDB and Redis here: https://taracot.org/source/db/mongo_redis_win64.zip. Unzip the files included to any folder on your hard disk and start using start.cmd. Two minimized console applications will be started, they should remain open every time you run TaracotJS server. For Linux/UNIX and MacOS-based operating systems you may install the corresponding MongoDB and Redis packages manually or compile from sources.
The quickest way to get started with TaracotJS is to utilize the executable taracotjs to generate an application as shown below.
Install taracotjs-generator:
npm install -g taracotjs-generator
Create Taracot JS instance:
taracotjs /tmp/foo && cd /tmp/foo
Install dependencies:
npm install
Edit config.js (using your favorite text editor), don't forget to set MongoDB connection URL and Redis port. You don't have to edit secrets and salt at this point, they will be auto-generated on the next step.
Perform system post-configuration:
cd bin && node install-system && node install-modules
Rock and Roll:
node webserver
If everything goes well, you will see the following message: “TaracotJS server listening on port: 3000” (3000 is the default port). Open up your favorite browser and open the following page: http://127.0.0.1:3000/.
Control panel is accessible via http://127.0.0.1:3000/cp/. Default username is admin, default password is admin.
NodizeCMS is still under heavy development, there's a ton of unimplemented features and even more bugs.
It's not ready for production yet, but you still can start to play with it and have plenty of fun !
nodejs >0.6.x
express
zappajs
sequelize
mysql
redis (optional)
Installation has been tested under Linux, MacOS and Windows.
Git, MySQL, Node.js and NPM have to be installed
Make a global install of CoffeeScript
npm install -g coffee-script
Retrieve NodizeCMS
git clone git://github.com/nodize/nodizecms.git
Install dependencies
cd nodizecms
npm install
Create a MySQL database and modify the file "/themes/pageone/settings/database.json"
mysqladmin create pageone
Start the server
coffee app.coffee
When your database is empty, a default "admin" user will be created with a random password at server startup :
._ _ _ _
| \ | | | (_)
| \| | ___ __| |_ _______
| . ` |/ _ \ / _` | |_ / _ \
| |\ | (_) | (_| | |/ / __/
\_| \_/\___/ \__,_|_/___\___|
listening on port 3000
SuperAdmin group created
Default user created, login = admin, password = 45A90 <----------- YOUR PASSWORD
Default lang created
Default menu created
Now you can access to the admistration module, open you browser on "http://127.0.0.1:3000/admin" (replace 127.0.0.1 by your server IP/URL if it's not running on the localhost).
If you're still there and that everything went fine, you should have a nice but empty backend.
Let's load some data : (replace "pageone" by your database name)
mysql pageone < themes/pageone/sql/pages.sql
or (if you have some access rights defined in MySQL) :
mysql pageone -u root -p < themes/pageone/sql/pages.sql
Now refresh your browser ! Do you see pages & articles ? Great !
Open a new browser window and enter this URL : "http://127.0.0.1:3000", if you are lucky, you're just looking at a dynamic webpage powered by Node.js & NodizeCMS !
Thank you for following this article.
SonicJs Node.js CMS Demo Part 1 Overview
1662955382
In today's post we will learn about 6 Essential Web Scraping Frameworks with JavaScript.
What is a Web Scraping?
Web scraping is the process of collecting structured web data in an automated fashion. It’s also called web data extraction. Some of the main use cases of web scraping include price monitoring, price intelligence, news monitoring, lead generation, and market research among many others.
In general, web data extraction is used by people and businesses who want to make use of the vast amount of publicly available web data to make smarter decisions.
If you’ve ever copied and pasted information from a website, you’ve performed the same function as any web scraper, only on a microscopic, manual scale. Unlike the mundane, mind-numbing process of manually extracting data, web scraping uses intelligent automation to retrieve hundreds, millions, or even billions of data points from the internet’s seemingly endless frontier.
Table of contents:
You can use WebParsy either as cli from your terminal or as a NodeJS library.
Install webparsy:
$ npm i webparsy -g
$ webparsy example/_weather.yml --customFlag "custom flag value"
Result:
{
"title": "Madrid, España Pronóstico del tiempo y condiciones meteorológicas - The Weather Channel | Weather.com",
"city": "Madrid, España",
"temp": 18
}
const webparsy = require('webparsy')
const parsingResult = await webparsy.init({
file: 'jobdefinition.yml'
flags: { ... } // optional
})
init(options)
options:
One of yaml
, file
or string
is required.
yaml
: A yaml npm module instance of the scraping definition.string
: The YAML definition, as a plain string.file
: The path for the YAML file containing the scraping definition.Additionally, you can pass a flags
object property to input additional values to your scraping process.
$ npm install crawler
const Crawler = require('crawler');
const c = new Crawler({
maxConnections: 10,
// This will be called for each crawled page
callback: (error, res, done) => {
if (error) {
console.log(error);
} else {
const $ = res.$;
// $ is Cheerio by default
//a lean implementation of core jQuery designed specifically for the server
console.log($('title').text());
}
done();
}
});
// Queue just one URL, with default callback
c.queue('http://www.amazon.com');
// Queue a list of URLs
c.queue(['http://www.google.com/','http://www.yahoo.com']);
// Queue URLs with custom callbacks & parameters
c.queue([{
uri: 'http://parishackers.org/',
jQuery: false,
// The global callback won't be called
callback: (error, res, done) => {
if (error) {
console.log(error);
} else {
console.log('Grabbed', res.body.length, 'bytes');
}
done();
}
}]);
// Queue some HTML code directly without grabbing (mostly for tests)
c.queue([{
html: '<p>This is a <strong>test</strong></p>'
}]);
Use rateLimit
to slow down when you are visiting web sites.
const Crawler = require('crawler');
const c = new Crawler({
rateLimit: 1000, // `maxConnections` will be forced to 1
callback: (err, res, done) => {
console.log(res.$('title').text());
done();
}
});
c.queue(tasks);//between two tasks, minimum time gap is 1000 (ms)
npm install --save simplecrawler
Initializing simplecrawler is a simple process. First, you require the module and instantiate it with a single argument. You then configure the properties you like (eg. the request interval), register a few event listeners, and call the start method. Let's walk through the process!
After requiring the crawler, we create a new instance of it. We supply the constructor with a URL that indicates which domain to crawl and which resource to fetch first.
var Crawler = require("simplecrawler");
var crawler = new Crawler("http://www.example.com/");
You can initialize the crawler with or without the new
operator. Being able to skip it comes in handy when you want to chain API calls.
var crawler = Crawler("http://www.example.com/")
.on("fetchcomplete", function () {
console.log("Fetched a resource!")
});
By default, the crawler will only fetch resources on the same domain as that in the URL passed to the constructor. But this can be changed through the crawler.domainWhitelist
property.
Now, let's configure some more things before we start crawling. Of course, you're probably wanting to ensure you don't take down your web server. Decrease the concurrency from five simultaneous requests - and increase the request interval from the default 250 ms like this:
crawler.interval = 10000; // Ten seconds
crawler.maxConcurrency = 3;
You can also define a max depth for links to fetch:
crawler.maxDepth = 1; // Only first page is fetched (with linked CSS & images)
// Or:
crawler.maxDepth = 2; // First page and discovered links from it are fetched
// Or:
crawler.maxDepth = 3; // Etc.
We recommend visiting the Introduction tutorial in Crawlee documentation for more information.
Crawlee requires Node.js 16 or higher.
The fastest way to try Crawlee out is to use the Crawlee CLI and choose the Getting started example. The CLI will install all the necessary dependencies and add boilerplate code for you to play with.
npx crawlee create my-crawler
cd my-crawler
npm start
If you prefer adding Crawlee into your own project, try the example below. Because it uses PlaywrightCrawler
we also need to install Playwright. It's not bundled with Crawlee to reduce install size.
npm install crawlee playwright
import { PlaywrightCrawler, Dataset } from 'crawlee';
// PlaywrightCrawler crawls the web using a headless
// browser controlled by the Playwright library.
const crawler = new PlaywrightCrawler({
// Use the requestHandler to process each of the crawled pages.
async requestHandler({ request, page, enqueueLinks, log }) {
const title = await page.title();
log.info(`Title of ${request.loadedUrl} is '${title}'`);
// Save results as JSON to ./storage/datasets/default
await Dataset.pushData({ title, url: request.loadedUrl });
// Extract links from the current page
// and add them to the crawling queue.
await enqueueLinks();
},
// Uncomment this option to see the browser window.
// headless: false,
});
// Add first URL to the queue and start the crawl.
await crawler.run(['https://crawlee.dev']);
By default, Crawlee stores data to ./storage
in the current working directory. You can override this directory via Crawlee configuration. For details, see Configuration guide, Request storage and Result storage.
Ayakashi's way of finding things in the page and using them is done with props and domQL.
Directly inspired by the relational database world (and SQL), domQL makes DOM access easy and readable no matter how obscure the page's structure is.
Props are the way to package domQL expressions as re-usable structures which can then be passed around to actions or to be used as models for data extraction.
Ready made actions so you can focus on what matters.
Easily handle infinite scrolling, single page navigation, events and more.
Plus, you can always build your own actions, either from scratch or by composing other actions.
Need to include a bunch of code, a library you made or a 3rd party module and make it available on a page?
Preloaders have you covered.
Automatically save your extracted data to all major SQL engines, JSON and CSV.
Need something more exotic or the ability to control exactly how the data is persisted?
Package and plug your custom logic as a script.
pjscrape is a framework for anyone who's ever wanted a command-line tool for web scraping using Javascript and jQuery. Built for PhantomJS, it allows you to scrape pages in a fully rendered, Javascript-enabled context from the command line, no browser required.
Thank you for following this article.
Introduction To Web Scraping With Javascript
1661435387
As technology advances, so must our methods of development. Check out this blog to know the top 10 web development frameworks that will be popular in 2022!
1659435972
Pendant longtemps, JavaScript a été le langage dominant dans le développement frontal en raison de sa capacité à s'exécuter nativement dans le navigateur et à interagir avec HTML et CSS via l'API DOM. Avec l'avènement de WebAssembly, les choses ont commencé à changer lentement. Des langages tels que Go, Rust, C, C++ et bien d'autres peuvent désormais s'exécuter dans le navigateur à des vitesses quasi natives, et Python n'a pas été laissé pour compte.
Avec l'introduction de PyScript, les développeurs frontend peuvent désormais créer des frontends riches avec Python. En outre, ils peuvent également puiser dans l'écosystème Python, qui contient des modules scientifiques utiles tels que NumPy , Matplotlib et bien d'autres.
Pour tirer le meilleur parti de ce tutoriel, vous aurez besoin de :
PyScript est un framework Web open source qui vous permet de créer des applications Web frontales à l'aide de Python. Avec PyScript, vous pouvez soit intégrer du code Python dans HTML, soit créer un lien vers un fichier Python et le code s'exécutera dans le navigateur, sans exécuter Python dans le backend.
PyScript a été créé par Anaconda et a été annoncé publiquement le 30 avril à PyCon US 2022. Au moment de la rédaction de cet article, PyScript est dans un état alpha et est en cours de développement, donc des changements de rupture et de nouvelles fonctionnalités sont à prévoir car il n'a pas n'a pas encore été publié de manière stable.
PyScript s'appuie sur Pyodide , qui porte CPython sur WebAssembly. WebAssembly est un format binaire de bas niveau qui vous permet d'écrire des programmes dans d'autres langages, qui sont ensuite exécutés dans le navigateur. Avec CPython dans WebAssembly, nous pouvons installer et exécuter des packages Python dans le navigateur, tandis que PyScript résume la plupart des opérations Pyodide, vous permettant de vous concentrer sur la création d'applications frontales avec Python dans le navigateur.
Avant de commencer à utiliser PyScript, créons le répertoire où résidera notre code.
Pour ce faire, ouvrez votre terminal et créez le répertoire du projet à l'aide de la mkdir
commande à l'emplacement de votre choix :
mkdir pyscript_demo
Ensuite, déplacez-vous dans le répertoire que vous venez de créer à l'aide de la cd
commande :
cd pyscript_demo
Souvent, les développeurs frontend utilisent des outils de formatage automatique comme Prettier dans leurs éditeurs de texte pour formater le code lors de l'enregistrement. Bien que cela fonctionne bien pour HTML, CSS et JavaScript, cela peut entraîner des problèmes dans le code Python car Python est strict en matière d'indentation.
Actuellement, les outils de formatage automatique comme Prettier ne reconnaissent pas la syntaxe PyScript, qui date d'environ deux mois au moment de la rédaction de cet article. Ces outils formatent automatiquement le code Python comme JavaScript, ce qui rompt l'indentation du code. Pour remédier à cela, nous désactiverons pour l'instant le formatage automatique de ce répertoire.
En supposant que vous utilisez VSCode, nous pouvons désactiver le formatage automatique comme suit.
Dans votre répertoire de projet, créez un .vscode
répertoire et naviguez dans le répertoire avec la commande suivante.
mkdir .vscode && cd .vscode
Ensuite, créez un settings.json
fichier et ajoutez le contenu suivant :
{
"editor.formatOnSave": false
}
Avec cela, la fonction de formatage automatique lors de l'enregistrement de ce répertoire a été désactivée dans VSCode et nous sommes maintenant prêts à commencer à utiliser PyScript.
Maintenant que notre répertoire est configuré pour PyScript, nous allons d'abord ajouter des liens vers les ressources PyScript comprenant un fichier CSS et un fichier JavaScript dans la <head>
section d'une page HTML.
Une fois les actifs ajoutés, vous pouvez utiliser PyScript dans un fichier HTML de deux manières :
<py-script>
balise d'un fichier HTML. La <py-script>
balise peut être ajoutée dans la balise <head>
ou <body>
en fonction de votre tâche à accomplir.py
extension, que vous pouvez ensuite référencer dans la <py-script>
balise à l'aide de l' src
attributLe moyen le plus simple et le plus rapide de commencer à utiliser PyScript consiste à intégrer du code Python dans le fichier HTML. Faisons cela!
Ouvrez votre éditeur de texte préféré, créez le hello-world.html
fichier et ajoutez le contenu suivant :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Hello World!</title>
<!-- linking to PyScript assets -->
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<!-- Put Python code inside the the <py-script> tag -->
<py-script>print("Hello World!")</py-script>
</body>
</html>
Dans la <head>
section, nous établissons un lien vers le pyscript.css
fichier, qui contient des styles pour les composants visuels PyScript, REPL, le chargeur PyScript, etc. Après cela, nous établissons un lien vers le pyscript.js
fichier, qui configure les fonctionnalités nécessaires à l'utilisation de PyScript, telles que la création de balises comme <py-script>
où vous pouvez écrire votre code Python.
Dans la <body>
balise, vous intégrez du code Python dans la <py-script>
balise. Nous gardons les choses simples pour l'instant, nous imprimons donc simplement Hello World
à l'utilisateur.
Assurez-vous d'enregistrer votre fichier à la racine du répertoire de votre projet et ouvrez le hello-world.html
fichier dans Chrome. Le chargement prendra quelques secondes, et une fois la page chargée, elle ressemblera à ceci :
Bien que l'insertion de code Python dans la <py-script>
balise fonctionne, une approche bien meilleure et plus évolutive consiste à ajouter le code dans un fichier externe et à le référencer dans le fichier HTML lorsque vous créez plus de pages HTML ou que vos scripts deviennent plus volumineux.
Voici quelques-unes des raisons pour lesquelles vous devriez envisager d'utiliser du code PyScript dans un fichier externe :
Pour utiliser PyScript en externe, nous allons créer un index.html
fichier, un fichier Python se terminant par une .py
extension contenant notre code Python, et enfin référencer le fichier Python dans le index.html
fichier.
index.html
fichierCréez un index.html
fichier et un lien vers les ressources PyScript :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Greetings!</title>
<!-- linking to PyScript assets -->
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
</body>
</html>
Le fichier ne fait pas grand-chose ; nous ne faisons que créer un lien vers les ressources PyScript. Pour le rendre plus utile, nous allons créer un main.py
fichier où résidera notre code Python.
main.py
fichierCréons une fonction Python qui imprime un message d'accueil.
Dans votre éditeur de texte, créez le main.py
fichier et ajoutez le code ci-dessous :
def greetings(name):
print(f'Hi, {name}')
greetings('John Doe')
La greetings()
fonction prend un name
paramètre et imprime un message d'accueil avec le nom stocké dans le name
paramètre. Lorsque nous appelons la greetings()
fonction avec John Doe
comme argument, elle imprime hi, John Doe
.
main.py
fichier dans le fichier HTMLMaintenant que vous avez créé le code Python, vous allez référencer le main.py
fichier dans le index.html
fichier.
Ouvrez le index.html
et ajoutez la ligne à l'intérieur de la <body>
balise :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Greetings!</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
// add the following line
<py-script src="./main.py"></py-script>
</body>
</html>
La <py-script>
balise a une src
balise qui accepte le chemin d'accès au fichier Python.
index.html
fichier dans le navigateurMaintenant que tout est en place, nous allons ouvrir le index.html
dans le navigateur.
Cependant, les navigateurs refuseront de charger et d'exécuter le fichier Python externe en raison de l' erreur de politique Cross-Origin Resource Sharing (CORS) . Pour résoudre ce problème, nous devrons utiliser un serveur. Heureusement que Python est livré avec un serveur Web que nous pouvons utiliser ! Le serveur n'a pas besoin d'être créé par Python, vous pouvez utiliser live-server ou n'importe quel serveur de votre choix.
Pour créer un serveur, ouvrez le terminal dans le répertoire racine de votre projet et exécutez la commande suivante :
python -m http.server
Ensuite, ouvrez Chrome et visitez http://0.0.0.0:8000/
. Le serveur chargera automatiquement le index.html
fichier et vous verrez ce qui suit :
Pour le reste de ce didacticiel, nous ferons référence à un fichier Python externe, ce qui nous obligera à utiliser un serveur pour éviter les erreurs CORS, et parfois nous intégrerons du code Python dans HTML par souci de brièveté.
PyScript est livré avec une boucle de lecture-évaluation-impression (REPL), que vous pouvez utiliser pour expérimenter et essayer le code Python.
Pour utiliser le REPL, ajoutez le <py-repl>
tag dans le <body>
tag de votre index.html
fichier :
<!DOCTYPE html>
...
<body>
<py-script src="./main.py"></py-script>
// add the following tag
<py-repl></py-repl>
</body>
</html>
Avec le serveur toujours en cours d'exécution, visitez http://0.0.0.0:8000/
. Vous verrez une nouvelle section où vous pourrez entrer du code Python.
Vous pouvez importer des modules, évaluer des expressions, créer des fonctions et bien d'autres choses encore. Pour voir à quoi correspond une expression, vous devez cliquer sur l' icône de lecture verte.
L'image suivante montre certaines des opérations que vous pouvez effectuer :
Maintenant que nous savons comment utiliser un REPL, nous allons maintenant apprendre à créer et à utiliser des modules dans PyScript.
Dans cette section, nous allons créer un module Python personnalisé et l'utiliser dans notre code. Nous utiliserons également des modules de la bibliothèque standard Python, ainsi que des modules tiers.
Pour utiliser les modules, nous allons introduire une nouvelle balise, <py-env>
, qui nous permet de référencer des modules ou des chemins de fichiers de modules.
Créons un module local contenant deux fonctions.
Créez un mathslib.py
fichier dans votre répertoire de projet et ajoutez le code ci-dessous :
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
Ici, nous avons créé deux fonctions qui effectuent des opérations d'addition et de soustraction.
Ensuite, créez un modules.html
fichier et ajoutez le contenu suivant :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>local modules</title>
<!-- linking to PyScript assets -->
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<py-env>
- paths:
- mathslib.py
</py-env>
<py-script>
from mathslib import subtract
print(subtract(8, 4))
<py-script>
</body>
</html>
Dans la <body>
balise, nous utilisons la <py-env>
balise, qui accepte une liste YAML qui a paths
pour clé. est le mathslib.py
chemin d'accès au fichier du module personnalisé relatif au modules.html
fichier. Une fois le chemin d'accès au module personnalisé spécifié, PyScript importera le module dans le fichier.
Avec le module chargé, dans la <py-script>
balise, nous importons la subtract()
fonction de mathslib.py
et invoquons la fonction avec les arguments 8
et 4
.
Avec le serveur en cours d'exécution, visitez http://0.0.0.0:8000/modules.html
et vous verrez une page similaire à celle-ci :
PyScript, avec l'aide de Pyodide, donne accès à de nombreux modules disponibles dans la bibliothèque standard Python qui sont prêts à être utilisés, à l'exception des suivants :
Visitez la documentation de Pyodide pour voir une liste complète. Notez également les modules inclus mais non fonctionnels, tels que les modules de multitraitement, de threading et de sockets.
Les modules de la bibliothèque standard sont disponibles dans l'espace de noms PyScript par défaut ; il vous suffit de les importer pour les utiliser dans le fichier.
Toujours dans le modules.html
fichier, modifiez le code Python dans la <py-script>
balise pour générer un nombre aléatoire à l'aide du random
module :
from mathslib import subtract
import random
print(subtract(8, 4))
print("random number generated: ")
print(random.randint(1, 12))
Visitez maintenant la http://0.0.0.0:8000/modules.html
page et vous verrez un nombre aléatoire généré chaque fois que vous actualisez la page :
Outre l'utilisation de modules Python intégrés, vous pouvez également utiliser des bibliothèques tierces fournies dans Pyodide, telles que :
Pour une liste complète des packages tiers pris en charge, consultez la documentation Pyodide ou gardez un œil attentif sur le référentiel Pyodide GitHub .
Pour ajouter un package tiers, créez un nouveau fichier HTML, third-party.html
, et ajoutez le code suivant :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>local modules</title>
<!-- linking to PyScript assets -->
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<!-- thirdparty dependencies added here -->
<py-env>
- numpy
- matplotlib
</py-env>
<py-script>
import numpy as np
import matplotlib.pyplot as plt
arr = np.array([1, 2, 3, 4, 5])
plt.plot(arr)
plt
<py-script>
</body>
</html>
Dans la <py-env>
balise, nous ajoutons une liste de packages tiers que nous souhaitons utiliser dans notre projet, qui sont les packages NumPy et Matplotlib. Ensuite, dans la <py-script>
balise, nous importons NumPy en tant que np
et Matplotlib en tant que plt
. Ensuite, nous appelons la array
méthode de NumPy, qui crée un tableau qui est ensuite stocké dans la arr
variable. Après cela, nous appelons la plot
méthode de Matplotlib avec le tableau arr
comme argument pour tracer un graphique.
Assurez-vous que votre fichier est enregistré et visitez la http://0.0.0.0:8000/third-party.html
page. Vous devriez voir un graphique semblable au suivant :
Maintenant que vous comprenez comment utiliser des modules intégrés personnalisés et des packages tiers, nous apprendrons comment accéder et manipuler les éléments HTML dans la section suivante.
Dans cette section, nous apprendrons comment sélectionner un élément HTML à l'aide d'un ID ou d'une classe CSS, modifier un élément, attacher des événements à un élément et créer de nouveaux éléments à l'aide de PyScript.
Element
classePyScript est livré avec la Element
classe, qui vous permet de sélectionner un élément HTML à l'aide de son ID.
Pour voir comment cela fonctionne, créez un elements.html
fichier et insérez le contenu suivant :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Element class</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<ul id="navigation">
<li class="home">home</li>
<li class="about">about</li>
<li class="services">services</li>
<li class="contact">contact</li></ul>
</div>
<div id="output"></div>
<py-script src="./access-elements.py"></py-script>
</body>
</html>
Dans la <body>
balise, nous avons un <ul>
élément avec un ID de navigation
. Nous utiliserons l'ID pour sélectionner cet élément à l'aide de la Element
classe. L'instance sélectionnée nous donnera des méthodes que nous pouvons utiliser pour sélectionner les descendants et les manipuler.
Une autre balise que nous utiliserons est le <div>
avec un ID de output
. Nous allons le modifier innerHTML
pour écrire une nouvelle valeur. Enfin, après la <div>
balise, nous établissons un lien vers le access-elements.py
fichier qui contiendra notre code Python. Il n'existe pas encore, alors allons-y et créons-le.
Une fois le fichier créé access-elements.py
, ajoutez-y le code suivant :
ul_element = Element("navigation")
first_element = ul_element.select('.home').add_class('first')
second_element = ul_element.select('.about').remove_class('about')
div_element = Element("output")
div_element.write("Value set from PyScript")
Dans le code précédent, nous utilisons la Element
classe pour accéder à l' <ul>
élément à l'aide de l' navigation
ID.
Lorsqu'un élément est sélectionné à l'aide de la Element
classe, vous pouvez tirer parti de certaines des méthodes suivantes :
write()
: Définit la innerHTML
valeurselect()
: Utilise un sélecteur CSS pour trouver des éléments descendantsadd_class()
: Ajoute une ou plusieurs classes à un élémentremove_class()
: Supprime une ou plusieurs classes d'un élémentDans la deuxième ligne, nous utilisons la select()
méthode pour sélectionner le premier élément enfant de l' <ul>
élément en utilisant son nom de classe, home
. Après avoir sélectionné l'enfant, nous appelons la add_class()
méthode pour ajouter une nouvelle classe first
à l' <li>
élément.
Dans la troisième ligne, nous accédons au deuxième élément enfant par son nom de classe about
, puis supprimons sa classe about
à l'aide de la remove_class()
méthode.
Ensuite, nous appelons la Element
classe avec l' ID output
, qui fournit une référence à l' <div>
élément qui réside après l' ul
élément dans le elements.html
fichier. Enfin, nous appelons la write()
méthode avec la chaîne Value set from PyScript
. La méthode définira la valeur de l' <div>
élément innerHTML
sur l'argument de chaîne.
Avec le serveur toujours actif, visitez http://0.0.0.0:8000/elements.html
et inspectez l' <ul>
élément. Vous verrez que le premier <li>
élément a maintenant une classe supplémentaire ( first
), le deuxième élément n'a pas de classe et l' div
élément a maintenant le texte que nous avons défini en Python.
Nous pouvons maintenant sélectionner des éléments HTML et effectuer quelques manipulations de base. Dans cette section, nous allons attacher un événement click à un élément et faire exécuter du code Python lorsque l'élément a été cliqué.
Créez un events.html
fichier et écrivez le code ci-dessous :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Adding Events</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<button id="click-btn" class="bg-blue-500 text-white" pys-onClick="handle_click">Click</button>
<div id="output"></div>
<py-script src="./event-handlers.py"></py-script>
</body>
</html>
Dans la <body>
balise, nous avons un <button>
avec un class
attribut contenant certaines classes qui font partie du pyscript.css
fichier. La <button>
balise a également un pys-onclick
attribut, qui attache un click
événement au bouton. L' pys-onclick
attribut accepte le nom de la fonction handle_click
, qui sera la fonction qui s'exécute lorsque le bouton est cliqué.
Ensuite, nous avons l' div
élément avec un ID de output
. Nous allons modifier l'élément innerHTML
avec la handle_click
fonction que nous définissons.
Enfin, nous établissons un lien vers le event-handlers.py
fichier, qui contiendra la fonction de gestionnaire d'événements.
Définissons le event-handlers.py
et ajoutons ce qui suit :
def handle_click(e):
pyscript.write("output", "you clicked the button")
La handle_click
fonction a un paramètre, e
qui est un objet événement transmis automatiquement à la fonction lorsque vous cliquez sur le bouton. A l'intérieur de la fonction, nous invoquons la write()
méthode de PyScript, qui prend deux arguments : l'ID de l'élément output
et la valeur que nous voulons écrire, dans notre cas, you clicked the button
.
Assurez-vous que votre serveur est en cours d'exécution :
python -m http.server
Ensuite, visitez l'URL http://0.0.0.0:8000/events.html
dans Chrome. Lorsque la page se charge, cliquez sur le bouton et un message indiquant "vous avez cliqué sur le bouton" apparaît :
PyScript est livré avec un js
module qui vous donne accès à des méthodes JavaScript, telles que querySelector()
, createElement()
, appendChild()
, etc., pour accéder et manipuler des éléments HTML. Avec ceux-ci, vous pourrez mélanger JavaScript et Python pour effectuer des manipulations DOM intéressantes. Voici un exemple:
import js
print(js.window.innerHeight)
nav = js.document.createElement("div")
js.document.body.prepend(nav)
js.console.log("nav element created")
Comme vous pouvez le voir, nous mélangeons des méthodes de code Python print()
avec JavaScript window
ou document
des propriétés.
Dans cette section, nous nous concentrerons principalement sur les document
méthodes, et commodément, PyScript les rend automatiquement disponibles dans la portée Python. Nous n'aurons même pas besoin d'importer le js
module pour utiliser les document
méthodes.
Créez un dom.html
fichier et ajoutez le code suivant :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Mixing JavaScript and Python</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<ul id="navigation">
</ul>
<py-script src="./js-dom.py"></py-script>
</body>
</html>
Dans la <body>
balise, nous n'avons qu'un <ul>
élément vide avec un ID de navigation
. Ensuite, nous référençons le js-dom.py
qui contiendra notre code Python.
Créez le js-dom.py
fichier et ajoutez le contenu suivant :
nav_parent = document.querySelector('#navigation')
nav_texts = ["home", "about", "services", "contact"]
for text in nav_texts:
nav_item = document.createElement("li")
nav_item.textContent = text
nav_item.className = "nav_element"
nav_parent.appendChild(nav_item)
Dans la première ligne, nous appelons la querySelector()
méthode du document
module avec #navigation
comme argument. La méthode trouvera et renverra un élément avec un ID de navigation
, qui est l' <ul>
élément dans le dom.html
fichier.
Dans la deuxième ligne, nous créons une liste de texte de navigation et la stockons dans la nav_texts
variable. Après cela, nous parcourons la nav_texts
liste. A chaque itération, nous invoquons la createElement()
méthode avec une chaîne li
pour créer un <li>
élément.
Ensuite, nous ajoutons du texte à l' <li>
élément à l'aide de la textContent
propriété et ajoutons un nom de classe nav_element
à l' <li>
élément à l'aide de la className
propriété. Enfin, nous ajoutons l' <li>
élément à l' <ul>
élément en appelant le appendChild()
avec l' nav_item
élément comme argument.
Assurez-vous que votre fichier est enregistré et que le serveur est toujours en cours d'exécution. Visitez http://0.0.0.0:8000/dom.html
, et vous verrez une page qui ressemble à ce qui suit :
Si vous creusez plus loin et inspectez les éléments, vous verrez que les <li>
éléments ont été créés avec le nom de classe nav_element
, que nous avons défini en Python :
Nous pouvons maintenant accéder et manipuler le DOM à l'aide de la Element
classe, attacher des événements aux éléments et utiliser JavaScript pour interroger et modifier le DOM. Ensuite, nous allons récupérer les données d'une API à l'aide de PyScript.
Dans cette section, nous utiliserons PyScript pour envoyer une GET
requête à une API afin de récupérer des données. L'API que nous utiliserons est l' API Random Data . Nous allons créer un bouton avec un événement click qui exécute une fonction qui appelle l'API chaque fois que le bouton est cliqué.
Créez un fetch_data.html
fichier dans votre répertoire et ajoutez le contenu suivant :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Fetch data from API</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<button id="get-name" class="bg-green-600 text-white" pys-onClick="get_random_name">Generate Random Name</button>
<div id="output"></div>
<py-script src="./fetch.py"></py-script>
</body>
</html>
Le code devrait être familier à ce stade. La partie la plus importante est la <button>
balise, qui a l' pys-onClick
attribut qui accepte la get_random_name()
fonction. La fonction résidera dans le fetch.py
fichier lié en bas. Continuons et créons le fichier.
Dans votre éditeur de texte, créez un nouveau fichier nommé fetch.py
avec le contenu suivant :
from pyodide.http import pyfetch
import asyncio
async def get_random_name(e):
response = await pyfetch(url="https://random-data-api.com/api/name/random_name", method="GET")
data = await response.json()
first_name = data.get('first_name')
middle_name = data.get('middle_name')
last_name = data.get('last_name')
output = f"Random name: {first_name} {middle_name} {last_name}"
pyscript.write('output', output)
Dans la première ligne, nous importons la pyfetch()
méthode du pyodide.http
module, ce qui nous permet de faire des requêtes réseau asynchrones. Dans la deuxième ligne, nous importons le asyncio
module, qui fait partie de la bibliothèque standard Python et fournit les mots-clés async
et await
utiles pour créer des fonctions asynchrones.
Ensuite, nous définissons une fonction asynchrone get_random_name()
en la préfixant avec le async
mot clé du asyncio
module. Au sein de la fonction, nous invoquons la pyfetch()
méthode qui accepte deux arguments :
URL
: Le point de terminaison de l'APImethod
: spécifie la méthode HTTP que vous souhaitez utiliser, qui est la GET
méthode ici.Lorsqu'il pyfetch()
s'exécute, il renvoie un objet, qui est ensuite stocké dans la response
variable. Dans la ligne qui suit, nous appelons le json()
sur l' response
objet pour analyser le JSON et renvoyer un dictionnaire Python, qui est ensuite stocké dans la data
variable.
Dans les lignes suivantes, vous extrayez le prénom, le deuxième prénom et le nom de famille du data
dict et les stockez dans leurs variables respectives. Enfin, nous concaténons les noms à l'aide des f-strings de Python et invoquons la pyscript.write()
méthode pour écrire les données dans l' <div>
élément avec un ID de output
.
Assurez-vous que votre serveur est en cours d'exécution et visitez la http://0.0.0.0:8000/fetch_data.html
page. Une fois la page chargée, cliquez sur le Generate Random Name
bouton. Vous verrez qu'un nouveau nom est généré à chaque clic sur le bouton :
localStorage
Dans cette section, nous utiliserons le stockage local pour enregistrer et récupérer des données. Le stockage local est un objet du navigateur Web qui peut stocker des données sans date d'expiration. Python peut utiliser le stockage local en l'important depuis le js
module.
Pour utiliser le stockage local, nous allons créer une zone de texte permettant aux utilisateurs de saisir des commentaires. S'ils souhaitent enregistrer le commentaire, ils cliqueront sur un save
bouton qui exécutera une fonction qui enregistre les données dans le stockage local. Chaque fois que la page est visitée, les données seront extraites du stockage local et la zone de texte sera définie sur les données.
Créez un storage.html
fichier et ajoutez le contenu suivant :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Store data in local storage</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<textarea id="comment" class="block border"></textarea>
<button id="save" class="bg-green-600 text-white"
pys-onClick="save_comment">Save</button>
<py-script src="./local-storage.py"></py-script>
</body>
</html>
Dans la <body>
balise, nous créons une <textarea>
balise avec un ID comment
. Nous utiliserons cet ID pour obtenir une référence de l'élément de zone de texte en Python. Ensuite, nous avons un bouton qui a save
pour identifiant et un événement click qui invoquera la fonction save_comment
, que nous n'avons pas encore définie. Enfin, nous référençons le local-storage.py
, qui contiendra notre code Python. Créons le fichier maintenant.
Créez local-storage.py
et ajoutez les éléments suivants :
from js import localStorage
def save_comment(e):
text = Element("comment").value
localStorage.setItem("comment", text)
if localStorage.getItem("comment"):
text_area = Element("comment")
text_area.write(localStorage.getItem("comment"))
Tout d'abord, nous importons l' localStorage
objet depuis le js
module. Ensuite, nous définissons la save_comment()
fonction, qui prend e
comme paramètre. Dans la fonction, nous invoquons la Element
classe avec l'ID comment
pour obtenir une référence de zone de texte. Une fois que la méthode trouve la zone de texte, nous utilisons la value
propriété pour obtenir le contenu de la zone de texte et stocker la valeur dans la text
variable. Dans la ligne suivante, nous invoquons la setItem()
méthode de l' localStorage
objet pour enregistrer le texte du commentaire dans l' localStorage
objet sous la comment
clé.
Désormais, la save_comment()
fonction ne s'exécutera que lorsque le save
bouton sera cliqué. Cependant, en procédant hors de la save_comment()
fonction, les lignes qui suivent la fonction ne s'exécuteront que lors du chargement de la page.
Lorsque la page est chargée pour la première fois, nous utilisons l' if
instruction pour vérifier si l' localStorage
objet contient des données sous la comment
clé. Si vrai, nous référençons la zone de texte à l'aide de la Element
classe et stockons son instance dans la text_area
variable. Ensuite, nous invoquons la write()
méthode de l' text_area
instance pour mettre à jour le contenu de la zone de texte avec les données du stockage local.
Assurez-vous que votre serveur est en cours d'exécution et visitez http://0.0.0.0:8000/storage.html
. Saisissez le texte de votre choix et cliquez sur le bouton Enregistrer .
Ensuite, actualisez l'URL et vous verrez que la zone de texte contient le texte que vous avez enregistré lors de la première visite.
Avec cela, vous savez maintenant comment tirer parti localStorage
de PyScript. Ensuite, nous allons lire un fichier dans le système de fichiers en utilisant PyScript.
Dans cette section, nous utiliserons PyScript pour lire les données d'un fichier en clair dans le système de fichiers local et ajouter son contenu dans le DOM.
Commençons par créer un fichier contenant les données que nous voulons lire. Dans le répertoire principal de votre projet, exécutez la commande suivante pour créer et déplacer dans un nouveau répertoire :
mkdir data && cd data
Ensuite, créez un names.txt
fichier et ajoutez le contenu suivant, qui sont des noms de frameworks Web Python :
Django
Flask
FastAPI
web2p
Enregistrez le fichier et revenez à la racine du répertoire de votre projet :
cd ..
Une fois le fichier créé, créez un file-system.html
fichier dans votre éditeur de texte avec les éléments suivants :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Read data from file system</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<py-env>
- paths:
- /data/names.txt
</py-env>
<ul id="frameworks">
</ul>
<py-script src="./read-file.py"></py-script>
</body>
</html>
Dans la <py-env>
balise, nous spécifions le chemin vers le names.txt
, qui est relatif au file-system.html
chemin. Ensuite, nous créons une <ul>
balise vide avec un frameworks
ID. Enfin, nous faisons référence au read-file.py
, que nous définirons bientôt.
Créez un read-file.py
avec le contenu suivant :
ul_element = document.querySelector("#frameworks")
with open("names.txt") as f:
for line in f:
li_element = document.createElement("li")
li_element.innerText = line
ul_element.appendChild(li_element)
Dans la première ligne, nous invoquons la querySelector()
méthode avec un ID selector #frameworks
, qui obtient une référence de l' <ul>
élément. Dans la deuxième ligne, nous appelons la open()
méthode avec le nom de fichier names.txt
et stockons l'objet fichier sous f
.
Dans l' with
instruction, nous parcourons chaque ligne stockée dans le fichier object f
. Lors de chaque itération, nous créons un <li>
élément en utilisant la méthode document
de l'objet createElement()
. Ensuite, nous définissons le <li>
contenu du texte sur la valeur de la line
variable à l'aide de la innerText
propriété de l' li_element
instance. Enfin, nous ajoutons l' <li>
élément à l' <ul>
élément en appelant le appendChild()
avec le li_element
comme argument.
Redémarrez le serveur (si vous l'avez arrêté avant) :
python -m http.server
Visitez l' http://0.0.0.0:8000/file-system.html
URL et vous verrez le contenu du fichier en clair s'afficher sur la page :
Si vous inspectez les éléments, vous verrez qu'il y a quatre <li>
éléments qui ont été ajoutés à l' <ul>
élément.
Avec cela, vous pouvez maintenant lire les fichiers dans le système de fichiers. Vous pouvez utiliser la même approche pour lire les fichiers CSV et de nombreux autres formats de fichiers.
Dans ce didacticiel, nous avons appris à utiliser le REPL PyScript, à créer des modules personnalisés, à utiliser des modules de la bibliothèque standard Python et à importer des modules tiers. Nous avons également appris à accéder et à manipuler des éléments à l'aide de PyScript, à effectuer des requêtes API, à utiliser localStorage
et à lire un fichier en texte brut à partir du système de fichiers.
Pour explorer davantage PyScript, visitez la page d'accueil de PyScript . De plus, consultez la page de documentation de Pyodide pour en savoir plus sur les possibilités qu'il permet dans le navigateur.
Source : https://blog.logrocket.com/pyscript-run-python-browser/
1659432540
Durante mucho tiempo, JavaScript ha sido el lenguaje dominante en el desarrollo de interfaz de usuario debido a su capacidad para ejecutarse de forma nativa en el navegador e interactuar con HTML y CSS a través de la API DOM. Con la llegada de WebAssembly, las cosas comenzaron a cambiar lentamente. Lenguajes como Go, Rust, C, C++ y muchos otros ahora pueden ejecutarse en el navegador a velocidades casi nativas, y Python no se ha quedado atrás.
Con la introducción de PyScript, los desarrolladores de interfaz ahora pueden crear interfaces enriquecidas con Python. Además, también pueden aprovechar el ecosistema de Python, que tiene módulos científicos útiles como NumPy , Matplotlib y muchos más.
Para aprovechar al máximo este tutorial, necesitará:
PyScript es un marco web de código abierto que le permite crear aplicaciones web frontend utilizando Python. Con PyScript, puede incrustar el código de Python en HTML o vincularlo a un archivo de Python y el código se ejecutará en el navegador, sin ejecutar Python en el backend.
PyScript fue creado por Anaconda y se anunció públicamente el 30 de abril en PyCon US 2022. En el momento de escribir este artículo, PyScript se encuentra en un estado alfa y se está desarrollando activamente, por lo que se esperan cambios importantes y características más nuevas ya que no ha sido lanzado establemente todavía.
PyScript se basa en Pyodide , que traslada CPython a WebAssembly. WebAssembly es un formato binario de bajo nivel que le permite escribir programas en otros idiomas, que luego se ejecutan en el navegador. Con CPython en WebAssembly, podemos instalar y ejecutar paquetes de Python en el navegador, mientras que PyScript abstrae la mayoría de las operaciones de Pyodide, lo que le permite concentrarse en crear aplicaciones frontend con Python en el navegador.
Antes de comenzar a usar PyScript, creemos el directorio donde residirá nuestro código.
Para hacer eso, abra su terminal y cree el directorio del proyecto usando el mkdir
comando en la ubicación que elija:
mkdir pyscript_demo
A continuación, acceda al directorio que acaba de crear con el cd
comando:
cd pyscript_demo
A menudo, los desarrolladores frontend usan herramientas de formato automático como Prettier en sus editores de texto para formatear el código al guardarlo. Si bien esto funciona bien para HTML, CSS y JavaScript, esto puede causar problemas en el código de Python porque Python es estricto con la sangría.
Actualmente, las herramientas de formato automático como Prettier no reconocen la sintaxis de PyScript, que tiene solo dos meses de antigüedad al momento de escribir este artículo. Estas herramientas dan formato automáticamente al código Python como JavaScript, lo que rompe la sangría del código. Para remediar esto, deshabilitaremos el formato automático para este directorio por ahora.
Suponiendo que está utilizando VSCode, podemos deshabilitar el formato automático de la siguiente manera.
En el directorio de su proyecto, cree un .vscode
directorio y navegue hasta el directorio con el siguiente comando.
mkdir .vscode && cd .vscode
A continuación, cree un settings.json
archivo y agregue los siguientes contenidos:
{
"editor.formatOnSave": false
}
Con eso, la función de formato automático al guardar para este directorio se ha deshabilitado en VSCode y ahora estamos listos para comenzar a usar PyScript.
Ahora que nuestro directorio está configurado para PyScript, primero agregaremos enlaces a los activos de PyScript que comprenden un archivo CSS y un archivo JavaScript en la <head>
sección de una página HTML.
Una vez que se han agregado los activos, puede usar PyScript en un archivo HTML de dos maneras:
<py-script>
etiqueta en un archivo HTML. La <py-script>
etiqueta se puede agregar en la etiqueta <head>
o <body>
dependiendo de su tarea en cuestión.py
la extensión, al que luego puede hacer referencia en la <py-script>
etiqueta usando el src
atributoLa forma más fácil y rápida de comenzar a usar PyScript es incrustar el código de Python en el archivo HTML. ¡Vamos a hacer eso!
Abra su editor de texto preferido, cree el hello-world.html
archivo y agregue los siguientes contenidos:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Hello World!</title>
<!-- linking to PyScript assets -->
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<!-- Put Python code inside the the <py-script> tag -->
<py-script>print("Hello World!")</py-script>
</body>
</html>
En la <head>
sección, vinculamos al pyscript.css
archivo, que contiene estilos para los componentes visuales de PyScript, REPL, el cargador de PyScript, etc. Después de eso, vinculamos al pyscript.js
archivo, que configura las funciones necesarias para usar PyScript, como crear etiquetas como <py-script>
donde puedes escribir tu código Python.
En la <body>
etiqueta, inserta el código de Python en la <py-script>
etiqueta. Mantenemos las cosas simples por ahora, así que solo imprimimos Hello World
para el usuario.
Asegúrese de guardar su archivo en la raíz del directorio de su proyecto y abra el hello-world.html
archivo en Chrome. Tardará un par de segundos en cargarse y, una vez que se haya cargado la página, se verá similar a esto:
Si bien funciona poner el código de Python en la <py-script>
etiqueta, un enfoque mucho mejor y más escalable es agregar el código en un archivo externo y hacer referencia a él en el archivo HTML a medida que crea más páginas HTML o sus scripts se hacen más grandes.
Las siguientes son algunas de las razones por las que debería considerar usar código PyScript en un archivo externo:
Para usar PyScript externamente, crearemos un index.html
archivo, un archivo de Python que termine con .py
la extensión que contiene nuestro código de Python, y finalmente haremos referencia al archivo de Python en el index.html
archivo.
index.html
archivoCree un index.html
archivo y enlace a los activos de PyScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Greetings!</title>
<!-- linking to PyScript assets -->
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
</body>
</html>
El archivo no está haciendo mucho; solo estamos vinculando a los recursos de PyScript. Para hacerlo más útil, crearemos un main.py
archivo donde residirá nuestro código Python.
main.py
archivoVamos a crear una función de Python que imprima un mensaje de saludo.
En su editor de texto, cree el main.py
archivo y agregue el código a continuación:
def greetings(name):
print(f'Hi, {name}')
greetings('John Doe')
La greetings()
función toma un name
parámetro e imprime un mensaje de saludo con el nombre almacenado en el name
parámetro. Cuando llamamos a la greetings()
función con John Doe
como argumento, imprime hi, John Doe
.
main.py
archivo en el archivo HTMLAhora que ha creado el código de Python, hará referencia al main.py
archivo en el index.html
archivo.
Abra index.html
y agregue la línea dentro de la <body>
etiqueta:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Greetings!</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
// add the following line
<py-script src="./main.py"></py-script>
</body>
</html>
La <py-script>
etiqueta tiene una src
etiqueta que acepta la ruta del archivo del archivo de Python.
index.html
archivo en el navegadorAhora que todo está en su lugar, abriremos el index.html
en el navegador.
Sin embargo, los navegadores se negarán a cargar y ejecutar el archivo Python externo debido al error de la política de uso compartido de recursos de origen cruzado (CORS) . Para solucionar esto, necesitaremos utilizar un servidor. ¡Qué bueno que Python viene con un servidor web que podemos usar! El servidor no necesita ser creado por Python, puede usar un servidor en vivo o cualquier servidor de su elección.
Para crear un servidor, abra la terminal en el directorio raíz de su proyecto y ejecute el siguiente comando:
python -m http.server
A continuación, abra Chrome y visite http://0.0.0.0:8000/
. El servidor cargará automáticamente el index.html
archivo y verá lo siguiente:
Para el resto de este tutorial, haremos referencia a un archivo de Python externo, lo que requerirá que usemos un servidor para evitar errores de CORS y, a veces, incrustaremos el código de Python en HTML por razones de brevedad.
PyScript viene con un Read-Eval-Print Loop (REPL), que puede usar para experimentar y probar el código de Python.
Para usar el REPL, agregue la <py-repl>
etiqueta en la <body>
etiqueta en su index.html
archivo:
<!DOCTYPE html>
...
<body>
<py-script src="./main.py"></py-script>
// add the following tag
<py-repl></py-repl>
</body>
</html>
Con el servidor aún en ejecución, visite http://0.0.0.0:8000/
. Verá una nueva sección donde puede ingresar el código de Python.
Puede importar módulos, evaluar expresiones, crear funciones y hacer muchas cosas más. Para ver a qué se evalúa una expresión, debe hacer clic en el ícono verde Reproducir .
La siguiente imagen muestra algunas de las operaciones que puede realizar:
Ahora que sabemos cómo usar un REPL, a continuación aprenderemos cómo crear y usar módulos en PyScript.
En esta sección, crearemos un módulo Python personalizado y lo usaremos en nuestro código. También usaremos módulos de la biblioteca estándar de Python, así como módulos de terceros.
Para usar módulos, introduciremos una nueva etiqueta, <py-env>
que nos permite hacer referencia a módulos o rutas de archivos de módulos.
Vamos a crear un módulo local que contenga dos funciones.
Cree un mathslib.py
archivo en el directorio de su proyecto y agregue el siguiente código:
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
Aquí creamos dos funciones que realizan operaciones de suma y resta.
A continuación, cree un modules.html
archivo y agregue los siguientes contenidos:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>local modules</title>
<!-- linking to PyScript assets -->
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<py-env>
- paths:
- mathslib.py
</py-env>
<py-script>
from mathslib import subtract
print(subtract(8, 4))
<py-script>
</body>
</html>
En la <body>
etiqueta, usamos la <py-env>
etiqueta, que acepta una lista YAML que tiene paths
como clave. es la mathslib.py
ruta del archivo del módulo personalizado en relación con el modules.html
archivo. Una vez que se especifica la ruta al módulo personalizado, PyScript importará el módulo en el archivo.
Con el módulo cargado, en la <py-script>
etiqueta, importamos la subtract()
función desde mathslib.py
e invocamos la función con los argumentos 8
y 4
.
Con el servidor funcionando, visita http://0.0.0.0:8000/modules.html
y verás una página similar a esta:
PyScript, con la ayuda de Pyodide, brinda acceso a una gran cantidad de módulos disponibles en la biblioteca estándar de Python que están listos para que los use, con la excepción de los siguientes:
Visite la documentación de Pyodide para ver una lista completa. Además, tome nota de los módulos que están incluidos pero que no funcionan, como los módulos de multiprocesamiento, subprocesamiento y sockets.
Los módulos de la biblioteca estándar están disponibles en el espacio de nombres de PyScript de forma predeterminada; solo necesita importarlos para usarlos en el archivo.
Todavía en el modules.html
archivo, modifique el código de Python en la <py-script>
etiqueta para generar un número aleatorio usando el random
módulo:
from mathslib import subtract
import random
print(subtract(8, 4))
print("random number generated: ")
print(random.randint(1, 12))
Ahora visite la http://0.0.0.0:8000/modules.html
página y verá un número aleatorio generado cada vez que actualice la página:
Además de usar módulos de Python incorporados, también puede usar bibliotecas de terceros incluidas en Pyodide, como:
Para obtener una lista completa de los paquetes de terceros admitidos, visite la documentación de Pyodide o esté atento al repositorio de Pyodide GitHub .
Para agregar un paquete de terceros, cree un nuevo archivo HTML third-party.html
y agregue el siguiente código:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>local modules</title>
<!-- linking to PyScript assets -->
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<!-- thirdparty dependencies added here -->
<py-env>
- numpy
- matplotlib
</py-env>
<py-script>
import numpy as np
import matplotlib.pyplot as plt
arr = np.array([1, 2, 3, 4, 5])
plt.plot(arr)
plt
<py-script>
</body>
</html>
En la <py-env>
etiqueta, agregamos una lista de paquetes de terceros que queremos usar en nuestro proyecto, que son los paquetes NumPy y Matplotlib. Luego, en la <py-script>
etiqueta, importamos NumPy como np
y Matplotlib como plt
. Después de esto, llamamos al array
método de NumPy, que crea una matriz que luego se almacena en la arr
variable. Después de eso, llamamos al plot
método de Matplotlib con la matriz arr
como argumento para trazar un gráfico.
Asegúrese de que su archivo esté guardado y visite la http://0.0.0.0:8000/third-party.html
página. Debería ver un gráfico similar al siguiente:
Ahora que comprende cómo usar módulos integrados personalizados y paquetes de terceros, aprenderemos cómo acceder y manipular elementos HTML en la siguiente sección.
En esta sección, aprenderemos cómo seleccionar un elemento HTML usando una ID o una clase CSS, modificar un elemento, adjuntar eventos a un elemento y crear nuevos elementos usando PyScript.
Element
clasePyScript se envía con la Element
clase, lo que le permite seleccionar un elemento HTML usando su ID.
Para ver cómo funciona, cree un elements.html
archivo e inserte los siguientes contenidos:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Element class</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<ul id="navigation">
<li class="home">home</li>
<li class="about">about</li>
<li class="services">services</li>
<li class="contact">contact</li></ul>
</div>
<div id="output"></div>
<py-script src="./access-elements.py"></py-script>
</body>
</html>
En la <body>
etiqueta, tenemos un <ul>
elemento con una ID de navigation
. Usaremos el ID para seleccionar este elemento usando la Element
clase. La instancia seleccionada nos dará métodos que podemos usar para seleccionar los descendientes y manipularlos.
Otra etiqueta que usaremos es <div>
con una ID de output
. Modificaremos su innerHTML
para escribir un nuevo valor. Finalmente, después de la <div>
etiqueta, vinculamos al access-elements.py
archivo que contendrá nuestro código Python. Todavía no existe, así que sigamos adelante y creémoslo.
Una vez que haya creado el access-elements.py
archivo, agréguele el siguiente código:
ul_element = Element("navigation")
first_element = ul_element.select('.home').add_class('first')
second_element = ul_element.select('.about').remove_class('about')
div_element = Element("output")
div_element.write("Value set from PyScript")
En el código anterior, usamos la Element
clase para acceder al <ul>
elemento usando la navigation
ID.
Cuando se selecciona un elemento usando la Element
clase, puede aprovechar algunos de los siguientes métodos:
write()
: establece el innerHTML
valorselect()
: utiliza un selector CSS para encontrar elementos descendientesadd_class()
: Agrega una o más clases a un elementoremove_class()
: Elimina una o más clases de un elementoEn la segunda línea, usamos el select()
método para seleccionar el primer elemento secundario del <ul>
elemento usando su nombre de clase, home
. Después de seleccionar el elemento secundario, llamamos al add_class()
método para agregar una nueva clase first
al <li>
elemento.
En la tercera línea, accedemos al segundo elemento secundario por su nombre de clase about
, y luego eliminamos su clase about
usando el remove_class()
método.
A continuación, llamamos a la Element
clase con el ID output
, que proporciona una referencia al <div>
elemento que reside después del ul
elemento en el elements.html
archivo. Finalmente, llamamos al write()
método con la cadena Value set from PyScript
. El método establecerá el valor del <div>
elemento innerHTML
en el argumento de cadena.
Con el servidor aún activo, visite http://0.0.0.0:8000/elements.html
e inspeccione el <ul>
elemento. Verá que el primer <li>
elemento ahora tiene una clase adicional ( first
), el segundo elemento no tiene clase y el div
elemento ahora tiene el texto que configuramos en Python.
Ahora podemos seleccionar elementos HTML y hacer algunas manipulaciones básicas. En esta sección, adjuntaremos un evento de clic a un elemento y haremos que el código de Python se ejecute cuando se haya hecho clic en el elemento.
Cree un events.html
archivo y escriba el código a continuación:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Adding Events</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<button id="click-btn" class="bg-blue-500 text-white" pys-onClick="handle_click">Click</button>
<div id="output"></div>
<py-script src="./event-handlers.py"></py-script>
</body>
</html>
En la <body>
etiqueta, tenemos un <button>
con un class
atributo que contiene algunas clases que forman parte del pyscript.css
archivo. La <button>
etiqueta también tiene un pys-onclick
atributo, que adjunta un click
evento al botón. El pys-onclick
atributo acepta el nombre de la función handle_click
, que será la función que se ejecutará cuando se haga clic en el botón.
A continuación, tenemos el div
elemento con un ID de output
. Modificaremos el elemento innerHTML
con la handle_click
función que definamos.
Finalmente, vinculamos al event-handlers.py
archivo, que contendrá la función del controlador de eventos.
Definamos el event-handlers.py
y agreguemos lo siguiente:
def handle_click(e):
pyscript.write("output", "you clicked the button")
La handle_click
función tiene un parámetro, e
que es un objeto de evento que se pasa automáticamente a la función cuando hace clic en el botón. Dentro de la función, invocamos el write()
método de PyScript, que toma dos argumentos: el ID del elemento output
y el valor que queremos escribir, en nuestro caso, you clicked the button
.
Asegúrese de que su servidor esté funcionando:
python -m http.server
Luego visite la URL http://0.0.0.0:8000/events.html
en Chrome. Cuando se cargue la página, haga clic en el botón y aparecerá un mensaje que dice "ha hecho clic en el botón":
PyScript viene con un js
módulo que le da acceso a métodos de JavaScript, como querySelector()
, createElement()
, appendChild()
, etc., para acceder y manipular elementos HTML. Con estos, podrá mezclar JavaScript y Python para hacer una manipulación genial del DOM. Aquí hay un ejemplo:
import js
print(js.window.innerHeight)
nav = js.document.createElement("div")
js.document.body.prepend(nav)
js.console.log("nav element created")
Como puede ver, estamos mezclando métodos de código de Python print()
junto con JavaScript window
o document
propiedades.
En esta sección, nos centraremos principalmente en los document
métodos y, convenientemente, PyScript lo pone a disposición en el alcance de Python automáticamente. Ni siquiera necesitaremos importar el js
módulo para usar los document
métodos.
Cree un dom.html
archivo y agregue el siguiente código:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Mixing JavaScript and Python</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<ul id="navigation">
</ul>
<py-script src="./js-dom.py"></py-script>
</body>
</html>
En la <body>
etiqueta, solo tenemos un <ul>
elemento vacío con una ID de navigation
. A continuación, hacemos referencia al js-dom.py
que contendrá nuestro código Python.
Cree el js-dom.py
archivo y agregue los siguientes contenidos:
nav_parent = document.querySelector('#navigation')
nav_texts = ["home", "about", "services", "contact"]
for text in nav_texts:
nav_item = document.createElement("li")
nav_item.textContent = text
nav_item.className = "nav_element"
nav_parent.appendChild(nav_item)
En la primera línea, llamamos al querySelector()
método del document
módulo con #navigation
como argumento. El método encontrará y devolverá un elemento con una ID de navigation
, que es el <ul>
elemento en el dom.html
archivo.
En la segunda línea, creamos una lista de texto de navegación y la almacenamos en la nav_texts
variable. Después de eso, iteramos sobre la nav_texts
lista. En cada iteración, invocamos el createElement()
método con una cadena li
para crear un <li>
elemento.
Después de esto, agregamos texto al <li>
elemento usando la textContent
propiedad y agregamos un nombre nav_element
de clase al <li>
elemento usando la className
propiedad. Finalmente, agregamos el <li>
elemento al <ul>
elemento llamando al appendChild()
con el nav_item
elemento como argumento.
Asegúrese de que su archivo esté guardado y que el servidor aún se esté ejecutando. Visite http://0.0.0.0:8000/dom.html
y verá una página similar a la siguiente:
Si profundiza más e inspecciona los elementos, verá que los <li>
elementos se han creado con el nombre de clase nav_element
, que configuramos en Python:
Ahora podemos acceder y manipular el DOM usando la Element
clase, adjuntar eventos a elementos y usar JavaScript para consultar y modificar el DOM. A continuación, buscaremos datos de una API usando PyScript.
En esta sección, usaremos PyScript para enviar una GET
solicitud a una API para recuperar datos. La API que usaremos es la API de datos aleatorios . Crearemos un botón con un evento de clic que ejecuta una función que llama a la API cada vez que se hace clic en el botón.
Cree un fetch_data.html
archivo en su directorio y agregue los siguientes contenidos:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Fetch data from API</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<button id="get-name" class="bg-green-600 text-white" pys-onClick="get_random_name">Generate Random Name</button>
<div id="output"></div>
<py-script src="./fetch.py"></py-script>
</body>
</html>
El código debe ser familiar en este punto. La parte más importante es la <button>
etiqueta, que tiene el pys-onClick
atributo que acepta la get_random_name()
función. La función residirá en el fetch.py
archivo vinculado en la parte inferior. Sigamos adelante y creemos el archivo.
En su editor de texto, cree un nuevo archivo llamado fetch.py
con los siguientes contenidos:
from pyodide.http import pyfetch
import asyncio
async def get_random_name(e):
response = await pyfetch(url="https://random-data-api.com/api/name/random_name", method="GET")
data = await response.json()
first_name = data.get('first_name')
middle_name = data.get('middle_name')
last_name = data.get('last_name')
output = f"Random name: {first_name} {middle_name} {last_name}"
pyscript.write('output', output)
En la primera línea, importamos el pyfetch()
método del pyodide.http
módulo, lo que nos permite realizar solicitudes de red asíncronas. En la segunda línea, importamos el asyncio
módulo, que es parte de la biblioteca estándar de Python y proporciona las palabras clave async
y await
que son útiles para crear funciones asíncronas.
A continuación, definimos una función asíncrona get_random_name()
prefijándola con la async
palabra clave del asyncio
módulo. Dentro de la función, invocamos el pyfetch()
método que acepta dos argumentos:
URL
: El punto final de la APImethod
: Especifique el método HTTP que desea utilizar, que es el GET
método aquí.Cuando pyfetch()
se ejecuta, devuelve un objeto, que luego se almacena en la response
variable. En la línea que sigue, llamamos json()
al response
objeto para analizar el JSON y devolver un diccionario de Python, que luego se almacena en la data
variable.
En las próximas líneas, extrae el primer nombre, el segundo nombre y el apellido del data
dict y los almacena en sus respectivas variables. Finalmente, concatenamos los nombres usando las cadenas f de Python e invocamos el pyscript.write()
método para escribir los datos en el <div>
elemento con una ID de output
.
Asegúrese de que su servidor esté funcionando y visite la http://0.0.0.0:8000/fetch_data.html
página. Una vez que se carga la página, haga clic en el Generate Random Name
botón. Verá que se genera un nuevo nombre cada vez que se hace clic en el botón:
localStorage
En esta sección, utilizaremos el almacenamiento local para guardar y recuperar datos. El almacenamiento local es un objeto en el navegador web que puede almacenar datos sin fecha de vencimiento. Python puede usar el almacenamiento local importándolo desde el js
módulo.
Para usar el almacenamiento local, crearemos un área de texto que permita a los usuarios escribir comentarios. Si quieren guardar el comentario, harán clic en un save
botón que ejecutará una función que guarda los datos en el almacenamiento local. Cada vez que se visita la página, los datos se recuperarán del almacenamiento local y el área de texto se configurará para los datos.
Cree un storage.html
archivo y agregue los siguientes contenidos:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Store data in local storage</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<textarea id="comment" class="block border"></textarea>
<button id="save" class="bg-green-600 text-white"
pys-onClick="save_comment">Save</button>
<py-script src="./local-storage.py"></py-script>
</body>
</html>
En la <body>
etiqueta, creamos una <textarea>
etiqueta con un ID comment
. Usaremos esta ID para obtener una referencia del elemento del área de texto en Python. A continuación, tenemos un botón que tiene save
como ID y un evento de clic que invocará la función save_comment
, que aún no hemos definido. Finalmente, hacemos referencia al local-storage.py
, que contendrá nuestro código de Python. Vamos a crear el archivo ahora.
Crea local-storage.py
y agrega lo siguiente:
from js import localStorage
def save_comment(e):
text = Element("comment").value
localStorage.setItem("comment", text)
if localStorage.getItem("comment"):
text_area = Element("comment")
text_area.write(localStorage.getItem("comment"))
Primero, importamos el localStorage
objeto del js
módulo. A continuación, definimos la save_comment()
función, que toma e
como parámetro. Dentro de la función, invocamos la Element
clase con el ID comment
para obtener una referencia del área de texto. Una vez que el método encuentra el área de texto, usamos la value
propiedad para obtener el contenido del área de texto y almacenar el valor en la text
variable. En la siguiente línea, invocamos el setItem()
método del localStorage
objeto para guardar el texto del comentario en el localStorage
objeto debajo de la comment
clave.
Ahora, la save_comment()
función solo se ejecutará cuando se haga clic en el save
botón. Sin embargo, procediendo fuera de la save_comment()
función, las líneas que siguen a la función se ejecutarán solo durante la carga de la página.
Cuando la página se carga por primera vez, usamos la if
declaración para verificar si el localStorage
objeto tiene datos debajo de la comment
clave. Si es verdadero, hacemos referencia al área de texto usando la Element
clase y almacenamos su instancia en la text_area
variable. A continuación, invocamos el write()
método de la text_area
instancia para actualizar el contenido del área de texto con los datos del almacenamiento local.
Asegúrese de que su servidor esté funcionando y visite http://0.0.0.0:8000/storage.html
. Ingrese cualquier texto que desee y haga clic en el botón Guardar .
A continuación, actualice la URL y verá que el área de texto contiene el texto que guardó en la visita inicial.
Con eso, ahora sabe cómo aprovechar localStorage
el uso de PyScript. A continuación, leeremos un archivo en el sistema de archivos usando PyScript.
En esta sección, usaremos PyScript para leer datos de un archivo de texto sin formato en el sistema de archivos local y agregar su contenido al DOM.
Primero, creemos un archivo que contenga los datos que queremos leer. En el directorio de su proyecto principal, ejecute el siguiente comando para crear y moverse a un nuevo directorio:
mkdir data && cd data
A continuación, cree un names.txt
archivo y agregue los siguientes contenidos, que son nombres de marcos web de Python:
Django
Flask
FastAPI
web2p
Guarde el archivo y vuelva a la raíz del directorio de su proyecto:
cd ..
Con el archivo creado, crea un file-system.html
archivo en tu editor de texto con lo siguiente:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Read data from file system</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<py-env>
- paths:
- /data/names.txt
</py-env>
<ul id="frameworks">
</ul>
<py-script src="./read-file.py"></py-script>
</body>
</html>
En la <py-env>
etiqueta, especificamos la ruta al names.txt
, que es relativa a la file-system.html
ruta. A continuación, creamos una <ul>
etiqueta vacía con una frameworks
identificación. Finalmente, hacemos referencia al read-file.py
, que definiremos pronto.
Crear un read-file.py
con los siguientes contenidos:
ul_element = document.querySelector("#frameworks")
with open("names.txt") as f:
for line in f:
li_element = document.createElement("li")
li_element.innerText = line
ul_element.appendChild(li_element)
En la primera línea, invocamos el querySelector()
método con un selector de ID #frameworks
, que obtiene una referencia del <ul>
elemento. En la segunda línea, llamamos al open()
método con el nombre del archivo names.txt
y almacenamos el objeto del archivo como f
.
Dentro de la with
declaración, iteramos sobre cada línea almacenada en el objeto de archivo f
. Durante cada iteración, creamos un <li>
elemento utilizando el método document
del objeto createElement()
. A continuación, establecemos el <li>
contenido del texto en el valor de la line
variable usando la innerText
propiedad de la li_element
instancia. Finalmente, agregamos el <li>
elemento al <ul>
elemento llamando a the appendChild()
con the li_element
como argumento.
Vuelva a iniciar el servidor (si lo detuvo antes):
python -m http.server
Visite la http://0.0.0.0:8000/file-system.html
URL y verá que el contenido del archivo de texto sin formato se muestra en la página:
Si inspecciona los elementos, verá que hay cuatro <li>
elementos que se agregaron al <ul>
elemento.
Con eso, ahora puede leer archivos en el sistema de archivos. Puede usar el mismo enfoque para leer archivos CSV y muchos otros formatos de archivo.
En este tutorial, aprendimos a usar PyScript REPL, crear módulos personalizados, usar módulos de la biblioteca estándar de Python e importar módulos de terceros. También aprendimos cómo acceder y manipular elementos usando PyScript, realizar solicitudes de API, usar localStorage
y leer un archivo de texto sin formato del sistema de archivos.
Para explorar más PyScript, visite la página de inicio de PyScript . Además, consulte la página de documentación de Pyodide para obtener más información sobre las posibilidades que habilita en el navegador.
Fuente: https://blog.logrocket.com/pyscript-run-python-browser/
1659432240
Por muito tempo, JavaScript tem sido a linguagem dominante no desenvolvimento front-end devido à sua capacidade de rodar nativamente no navegador e interagir com HTML e CSS através da API DOM. Com o advento do WebAssembly, as coisas começaram a mudar lentamente. Linguagens como Go, Rust, C, C++ e muitas outras agora podem ser executadas no navegador em velocidades quase nativas, e o Python não foi deixado para trás.
Com a introdução do PyScript, os desenvolvedores de front-end agora podem criar front-ends avançados com Python. Além disso, eles também podem acessar o ecossistema Python, que possui módulos científicos úteis, como NumPy , Matplotlib e muitos mais.
Para aproveitar ao máximo este tutorial, você precisará de:
O PyScript é uma estrutura da Web de código aberto que permite criar aplicativos da Web de front-end usando Python. Com o PyScript, você pode incorporar o código Python em HTML ou vincular a um arquivo Python e o código será executado no navegador - sem executar o Python no back-end.
O PyScript foi criado pela Anaconda e foi anunciado publicamente em 30 de abril na PyCon US 2022. No momento da redação, o PyScript está em um estado alfa e está sendo desenvolvido ativamente, portanto, alterações importantes e recursos mais novos são esperados, pois não foi liberado de forma estável ainda.
O PyScript baseia-se no Pyodide , que porta o CPython para o WebAssembly. WebAssembly é um formato binário de baixo nível que permite escrever programas em outras linguagens, que são executados no navegador. Com o CPython no WebAssembly, podemos instalar e executar pacotes Python no navegador, enquanto o PyScript abstrai a maioria das operações do Pyodide, permitindo que você se concentre na criação de aplicativos front-end com Python no navegador.
Antes de começarmos a usar o PyScript, vamos criar o diretório onde nosso código residirá.
Para isso, abra seu terminal e crie o diretório do projeto usando o mkdir
comando no local de sua escolha:
mkdir pyscript_demo
Em seguida, vá para o diretório que você acabou de criar usando o cd
comando:
cd pyscript_demo
Muitas vezes, os desenvolvedores de front-end usam ferramentas de formatação automática como o Prettier em seus editores de texto para formatar o código ao salvar. Embora isso funcione bem para HTML, CSS e JavaScript, isso pode causar problemas no código Python porque o Python é rigoroso quanto ao recuo.
Atualmente, ferramentas de formatação automática como o Prettier não reconhecem a sintaxe PyScript, que tem apenas cerca de dois meses no momento da redação deste artigo. Essas ferramentas formatam automaticamente o código Python como JavaScript, que quebra o recuo do código. Para remediar isso, vamos desabilitar a formatação automática para este diretório por enquanto.
Supondo que você esteja usando o VSCode, podemos desabilitar a formatação automática da seguinte maneira.
No diretório do projeto, crie um .vscode
diretório e navegue até o diretório com o seguinte comando.
mkdir .vscode && cd .vscode
Em seguida, crie um settings.json
arquivo e adicione o seguinte conteúdo:
{
"editor.formatOnSave": false
}
Com isso, o recurso de formatação automática ao salvar para este diretório foi desabilitado no VSCode e agora estamos prontos para começar a usar o PyScript.
Agora que nosso diretório está configurado para PyScript, primeiro adicionaremos links para os ativos PyScript compostos por um arquivo CSS e um arquivo JavaScript na <head>
seção de uma página HTML.
Depois que os ativos forem adicionados, você poderá usar o PyScript em um arquivo HTML de duas maneiras:
<py-script>
tag em um arquivo HTML. A <py-script>
tag pode ser adicionada na tag <head>
ou <body>
dependendo da sua tarefa em mãos.py
extensão, que você pode referenciar na <py-script>
tag usando o src
atributoA maneira mais fácil e rápida de começar a usar o PyScript é incorporar o código Python no arquivo HTML. Vamos fazer isso!
Abra seu editor de texto preferido, crie o hello-world.html
arquivo e adicione o seguinte conteúdo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Hello World!</title>
<!-- linking to PyScript assets -->
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<!-- Put Python code inside the the <py-script> tag -->
<py-script>print("Hello World!")</py-script>
</body>
</html>
Na <head>
seção, vinculamos ao pyscript.css
arquivo, que contém estilos para componentes visuais do PyScript, REPL, carregador PyScript, etc. Depois, vinculamos ao pyscript.js
arquivo, que configura os recursos necessários para usar o PyScript, como criar tags como <py-script>
onde você pode escrever seu código Python.
Na <body>
tag, você incorpora o código Python na <py-script>
tag. Estamos mantendo as coisas simples por enquanto, então apenas imprimimos Hello World
para o usuário.
Certifique-se de salvar seu arquivo na raiz do diretório do seu projeto e abra o hello-world.html
arquivo no Chrome. Levará alguns segundos para carregar e, depois que a página for carregada, ela será semelhante a esta:
Embora colocar o código Python na <py-script>
tag funcione, uma abordagem muito melhor e mais escalável é adicionar o código em um arquivo externo e referenciá-lo no arquivo HTML à medida que você cria mais páginas HTML ou seus scripts ficam maiores.
A seguir estão alguns dos motivos pelos quais você deve considerar o uso do código PyScript em um arquivo externo:
Para usar o PyScript externamente, criaremos um index.html
arquivo, um arquivo Python terminando com .py
extensão contendo nosso código Python e, finalmente, referenciaremos o arquivo Python no index.html
arquivo.
index.html
arquivoCrie um index.html
arquivo e vincule aos ativos PyScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Greetings!</title>
<!-- linking to PyScript assets -->
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
</body>
</html>
O arquivo não está fazendo muito; estamos apenas vinculando aos recursos do PyScript. Para torná-lo mais útil, criaremos um main.py
arquivo onde nosso código Python residirá.
main.py
arquivoVamos criar uma função Python que imprima uma mensagem de saudação.
Em seu editor de texto, crie o main.py
arquivo e adicione o código abaixo:
def greetings(name):
print(f'Hi, {name}')
greetings('John Doe')
A greetings()
função recebe um name
parâmetro e imprime uma mensagem de saudação com o nome armazenado no name
parâmetro. Quando chamamos a greetings()
função with John Doe
como argumento, ela imprime hi, John Doe
.
main.py
arquivo no arquivo HTMLAgora que você criou o código Python, você fará referência ao main.py
arquivo no index.html
arquivo.
Abra o index.html
e adicione a linha dentro da <body>
tag:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Greetings!</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
// add the following line
<py-script src="./main.py"></py-script>
</body>
</html>
A <py-script>
tag tem uma src
tag, que aceita o caminho do arquivo Python.
index.html
arquivo no navegadorAgora que tudo está no lugar, vamos abrir o index.html
no navegador.
No entanto, os navegadores se recusarão a carregar e executar o arquivo Python externo devido ao erro de política Cross-Origin Resource Sharing (CORS) . Para resolver isso, precisaremos usar um servidor. Ainda bem que o Python vem com um servidor web que podemos usar! O servidor não precisa ser criado pelo Python, você pode usar o live-server ou qualquer servidor de sua escolha.
Para criar um servidor, abra o terminal no diretório raiz do seu projeto e execute o seguinte comando:
python -m http.server
Em seguida, abra o Chrome e visite http://0.0.0.0:8000/
. O servidor carregará automaticamente o index.html
arquivo e você verá o seguinte:
No restante deste tutorial, faremos referência a um arquivo Python externo, que exigirá o uso de um servidor para evitar erros de CORS e, às vezes, incorporaremos código Python em HTML por questões de brevidade.
O PyScript vem com um Read-Eval-Print Loop (REPL), que você pode usar para experimentar e testar o código Python.
Para usar o REPL, adicione a <py-repl>
tag na <body>
tag do seu index.html
arquivo:
<!DOCTYPE html>
...
<body>
<py-script src="./main.py"></py-script>
// add the following tag
<py-repl></py-repl>
</body>
</html>
Com o servidor ainda em execução, visite http://0.0.0.0:8000/
. Você verá uma nova seção onde você pode inserir o código Python.
Você pode importar módulos, avaliar expressões, criar funções e fazer muitas outras coisas. Para ver o que uma expressão avalia, você precisa clicar no ícone verde Reproduzir .
A imagem a seguir mostra algumas das operações que você pode fazer:
Agora que já sabemos como usar um REPL, a seguir vamos aprender como criar e usar módulos em PyScript.
Nesta seção, criaremos um módulo Python personalizado e o usaremos em nosso código. Também usaremos módulos da biblioteca padrão do Python, bem como módulos de terceiros.
Para usar módulos, vamos introduzir uma nova tag, <py-env>
, que nos permite referenciar módulos ou caminhos de arquivos de módulos.
Vamos criar um módulo local contendo duas funções.
Crie um mathslib.py
arquivo no diretório do seu projeto e adicione o código abaixo:
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
Aqui criamos duas funções que fazem operações de adição e subtração.
Em seguida, crie um modules.html
arquivo e adicione o seguinte conteúdo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>local modules</title>
<!-- linking to PyScript assets -->
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<py-env>
- paths:
- mathslib.py
</py-env>
<py-script>
from mathslib import subtract
print(subtract(8, 4))
<py-script>
</body>
</html>
Na <body>
tag, usamos a <py-env>
tag, que aceita uma lista YAML que tem paths
como chave. O mathslib.py
é o caminho do arquivo do módulo personalizado em relação ao modules.html
arquivo. Depois que o caminho para o módulo personalizado for especificado, o PyScript importará o módulo no arquivo.
Com o módulo carregado, na <py-script>
tag, importamos a subtract()
função mathslib.py
e invocamos a função com os argumentos 8
e 4
.
Com o servidor rodando, acesse http://0.0.0.0:8000/modules.html
e você verá uma página parecida com esta:
O PyScript, com a ajuda do Pyodide, fornece acesso a muitos módulos disponíveis na biblioteca padrão do Python que estão prontos para uso, com exceção dos seguintes:
Visite a documentação do Pyodide para ver uma lista abrangente. Além disso, observe os módulos incluídos, mas não funcionais, como os módulos de multiprocessamento, encadeamento e soquetes.
Os módulos da biblioteca padrão estão disponíveis no namespace PyScript por padrão; você só precisa importá-los para usá-los no arquivo.
Ainda no modules.html
arquivo, modifique o código Python na <py-script>
tag para gerar um número aleatório usando o random
módulo:
from mathslib import subtract
import random
print(subtract(8, 4))
print("random number generated: ")
print(random.randint(1, 12))
Agora visite a http://0.0.0.0:8000/modules.html
página e você verá um número aleatório gerado cada vez que atualizar a página:
Além de usar módulos Python embutidos, você também pode usar bibliotecas de terceiros enviadas no Pyodide, como:
Para obter uma lista completa de pacotes de terceiros suportados, visite a documentação do Pyodide ou fique de olho no repositório GitHub do Pyodide .
Para adicionar um pacote de terceiros, crie um novo arquivo HTML third-party.html
, e adicione o seguinte código:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>local modules</title>
<!-- linking to PyScript assets -->
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<!-- thirdparty dependencies added here -->
<py-env>
- numpy
- matplotlib
</py-env>
<py-script>
import numpy as np
import matplotlib.pyplot as plt
arr = np.array([1, 2, 3, 4, 5])
plt.plot(arr)
plt
<py-script>
</body>
</html>
Na <py-env>
tag, adicionamos uma lista de pacotes de terceiros que queremos usar em nosso projeto, que são os pacotes NumPy e Matplotlib. Em seguida, na <py-script>
tag, importamos NumPy as np
e Matplotlib as plt
. Em seguida, chamamos o array
método de NumPy, que cria um array que é armazenado na arr
variável. Depois disso, chamamos o plot
método do Matplotlib com o array arr
como argumento para traçar um gráfico.
Certifique-se de que seu arquivo está salvo e visite a http://0.0.0.0:8000/third-party.html
página. Você deverá ver um gráfico semelhante ao seguinte:
Agora que você entende como usar módulos personalizados e embutidos e pacotes de terceiros, aprenderemos como acessar e manipular elementos HTML na próxima seção.
Nesta seção, aprenderemos como selecionar um elemento HTML usando um ID ou uma classe CSS, modificar um elemento, anexar eventos a um elemento e criar novos elementos usando PyScript.
Element
classeO PyScript é fornecido com a Element
classe, que permite selecionar um elemento HTML usando seu ID.
Para ver como funciona, crie um elements.html
arquivo e insira o seguinte conteúdo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Element class</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<ul id="navigation">
<li class="home">home</li>
<li class="about">about</li>
<li class="services">services</li>
<li class="contact">contact</li></ul>
</div>
<div id="output"></div>
<py-script src="./access-elements.py"></py-script>
</body>
</html>
Na <body>
tag, temos um <ul>
elemento com um ID de navigation
. Usaremos o ID para selecionar este elemento usando a Element
classe. A instância selecionada nos dará métodos que podemos usar para selecionar os descendentes e manipulá-los.
Outra tag que usaremos é a <div>
com um ID de output
. Vamos modificá-lo innerHTML
para escrever um novo valor. Por fim, após a <div>
tag, vinculamos ao access-elements.py
arquivo que conterá nosso código Python. Ele ainda não existe, então vamos em frente e criá-lo.
Depois de criar o access-elements.py
arquivo, adicione o seguinte código a ele:
ul_element = Element("navigation")
first_element = ul_element.select('.home').add_class('first')
second_element = ul_element.select('.about').remove_class('about')
div_element = Element("output")
div_element.write("Value set from PyScript")
No código anterior, usamos a Element
classe para acessar o <ul>
elemento usando o navigation
ID.
Quando um elemento é selecionado usando a Element
classe, você pode aproveitar alguns dos seguintes métodos:
write()
: Define o innerHTML
valorselect()
: usa um seletor CSS para encontrar elementos descendentesadd_class()
: Adiciona uma ou mais classes a um elementoremove_class()
: Remove uma ou mais classes de um elementoNa segunda linha, usamos o select()
método para selecionar o primeiro elemento filho do <ul>
elemento usando seu nome de classe, home
. Após selecionar o filho, chamamos o add_class()
método para adicionar uma nova classe first
ao <li>
elemento.
Na terceira linha, acessamos o segundo elemento filho por seu nome de classe about
, e, em seguida, removemos sua classe about
usando o remove_class()
método.
Em seguida, chamamos a Element
classe com o ID output
, que fornece uma referência ao <div>
elemento que reside após o ul
elemento no elements.html
arquivo. Por fim, chamamos o write()
método com a string Value set from PyScript
. O método definirá o valor do <div>
elemento innerHTML
para o argumento de string.
Com o servidor ainda ativo, visite http://0.0.0.0:8000/elements.html
e inspecione o <ul>
elemento. Você verá que o primeiro <li>
elemento agora tem uma classe extra ( first
), o segundo elemento não tem classe e o div
elemento agora tem o texto que definimos em Python.
Agora podemos selecionar elementos HTML e fazer algumas manipulações básicas. Nesta seção, anexaremos um evento click a um elemento e faremos com que o código Python seja executado quando o elemento for clicado.
Crie um events.html
arquivo e escreva o código abaixo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Adding Events</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<button id="click-btn" class="bg-blue-500 text-white" pys-onClick="handle_click">Click</button>
<div id="output"></div>
<py-script src="./event-handlers.py"></py-script>
</body>
</html>
Na <body>
tag, temos um <button>
com um class
atributo contendo algumas classes que fazem parte do pyscript.css
arquivo. A <button>
tag também possui um pys-onclick
atributo, que anexa um click
evento ao botão. O pys-onclick
atributo aceita o nome da função handle_click
, que será a função que será executada quando o botão for clicado.
Em seguida, temos o div
elemento com um ID de output
. Vamos modificar o elemento innerHTML
com a handle_click
função que definimos.
Por fim, vinculamos ao event-handlers.py
arquivo, que conterá a função do manipulador de eventos.
Vamos definir o event-handlers.py
e adicionar o seguinte:
def handle_click(e):
pyscript.write("output", "you clicked the button")
A handle_click
função tem um parâmetro, e
, que é um objeto de evento passado automaticamente para a função quando você clica no botão. Dentro da função, invocamos o write()
método do PyScript, que recebe dois argumentos: o ID do elemento output
e o valor que queremos escrever, no nosso caso, you clicked the button
.
Verifique se o seu servidor está rodando:
python -m http.server
Em seguida, visite o URL http://0.0.0.0:8000/events.html
no Chrome. Quando a página carregar, clique no botão e uma mensagem dizendo “você clicou no botão” aparecerá:
O PyScript vem com um js
módulo que dá acesso a métodos JavaScript, como querySelector()
, createElement()
, appendChild()
, etc., para acessar e manipular elementos HTML. Com eles, você poderá misturar JavaScript e Python para fazer uma manipulação legal do DOM. Aqui está um exemplo:
import js
print(js.window.innerHeight)
nav = js.document.createElement("div")
js.document.body.prepend(nav)
js.console.log("nav element created")
Como você pode ver, estamos misturando métodos de código Python como print()
JavaScript window
ou document
propriedades.
Nesta seção, focaremos principalmente nos document
métodos e, convenientemente, o PyScript o disponibiliza no escopo do Python automaticamente. Nem precisaremos importar o js
módulo para usar os document
métodos.
Crie um dom.html
arquivo e adicione o seguinte código:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Mixing JavaScript and Python</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<ul id="navigation">
</ul>
<py-script src="./js-dom.py"></py-script>
</body>
</html>
Na <body>
tag, temos apenas um <ul>
elemento vazio com ID de navigation
. Em seguida, fazemos referência ao js-dom.py
que conterá nosso código Python.
Crie o js-dom.py
arquivo e adicione o seguinte conteúdo:
nav_parent = document.querySelector('#navigation')
nav_texts = ["home", "about", "services", "contact"]
for text in nav_texts:
nav_item = document.createElement("li")
nav_item.textContent = text
nav_item.className = "nav_element"
nav_parent.appendChild(nav_item)
Na primeira linha, chamamos o querySelector()
método do document
módulo com #navigation
como argumento. O método encontrará e retornará um elemento com um ID de navigation
, que é o <ul>
elemento no dom.html
arquivo.
Na segunda linha, criamos uma lista de texto de navegação e a armazenamos na nav_texts
variável. Depois disso, iteramos sobre a nav_texts
lista. Em cada iteração, invocamos o createElement()
método com uma string li
para criar um <li>
elemento.
Depois disso, adicionamos texto ao <li>
elemento usando a textContent
propriedade e adicionamos um nome de classe nav_element
ao <li>
elemento usando a className
propriedade. Finalmente, anexamos o <li>
elemento ao <ul>
elemento chamando the appendChild()
com o nav_item
elemento como argumento.
Certifique-se de que seu arquivo esteja salvo e que o servidor ainda esteja em execução. Visite http://0.0.0.0:8000/dom.html
e você verá uma página semelhante à seguinte:
Se você cavar mais fundo e inspecionar os elementos, verá que os <li>
elementos foram criados com o nome da classe nav_element
, que definimos em Python:
Agora podemos acessar e manipular o DOM usando a Element
classe, anexar eventos a elementos e usar JavaScript para consultar e modificar o DOM. Em seguida, buscaremos dados de uma API usando PyScript.
Nesta seção, usaremos o PyScript para enviar uma GET
solicitação a uma API para recuperar dados. A API que usaremos é a Random Data API . Vamos criar um botão com um evento click que executa uma função que chama a API toda vez que o botão é clicado.
Crie um fetch_data.html
arquivo em seu diretório e adicione o seguinte conteúdo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Fetch data from API</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<button id="get-name" class="bg-green-600 text-white" pys-onClick="get_random_name">Generate Random Name</button>
<div id="output"></div>
<py-script src="./fetch.py"></py-script>
</body>
</html>
O código deve ser familiar neste momento. A parte mais importante é a <button>
tag, que tem o pys-onClick
atributo que aceita a get_random_name()
função. A função residirá no fetch.py
arquivo vinculado na parte inferior. Vamos em frente e criar o arquivo.
Em seu editor de texto, crie um novo arquivo chamado fetch.py
com o seguinte conteúdo:
from pyodide.http import pyfetch
import asyncio
async def get_random_name(e):
response = await pyfetch(url="https://random-data-api.com/api/name/random_name", method="GET")
data = await response.json()
first_name = data.get('first_name')
middle_name = data.get('middle_name')
last_name = data.get('last_name')
output = f"Random name: {first_name} {middle_name} {last_name}"
pyscript.write('output', output)
Na primeira linha, importamos o pyfetch()
método do pyodide.http
módulo, o que nos permite fazer requisições de rede assíncronas. Na segunda linha, importamos o asyncio
módulo, que faz parte da biblioteca padrão do Python e fornece as palavras-chave async
e await
que são úteis para criar funções assíncronas.
Em seguida, definimos uma função assíncrona get_random_name()
prefixando-a com a async
palavra-chave do asyncio
módulo. Dentro da função, invocamos o pyfetch()
método que aceita dois argumentos:
URL
: o ponto de extremidade da APImethod
: especifica o método HTTP que você deseja usar, que é o GET
método aqui.Quando pyfetch()
executado, ele retorna um objeto, que é então armazenado na response
variável. Na linha a seguir, chamamos json()
on o response
objeto para analisar o JSON e retornar um dicionário Python, que é armazenado na data
variável.
Nas próximas linhas, você extrai o nome, o nome do meio e o sobrenome do data
dict e os armazena em suas respectivas variáveis. Por fim, concatenamos os nomes usando as strings f do Python e invocamos o pyscript.write()
método para escrever os dados no <div>
elemento com um ID de output
.
Verifique se o seu servidor está funcionando e visite a http://0.0.0.0:8000/fetch_data.html
página. Quando a página carregar, clique no Generate Random Name
botão. Você verá que um novo nome é gerado cada vez que o botão é clicado:
localStorage
Nesta seção, usaremos o armazenamento local para salvar e recuperar dados. O armazenamento local é um objeto no navegador da Web que pode armazenar dados sem data de expiração. O Python pode usar o armazenamento local importando-o do js
módulo.
Para usar o armazenamento local, criaremos uma área de texto que permite aos usuários digitar comentários. Se eles quiserem salvar o comentário, eles clicarão em um save
botão que executará uma função que salva os dados no armazenamento local. Toda vez que a página for visitada, os dados serão recuperados do armazenamento local e a área de texto será definida para os dados.
Crie um storage.html
arquivo e adicione o seguinte conteúdo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Store data in local storage</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<textarea id="comment" class="block border"></textarea>
<button id="save" class="bg-green-600 text-white"
pys-onClick="save_comment">Save</button>
<py-script src="./local-storage.py"></py-script>
</body>
</html>
Na <body>
tag, criamos uma <textarea>
tag com um ID comment
. Usaremos esse ID para obter uma referência do elemento text area em Python. Em seguida, temos um botão que tem save
como ID e um evento click que invocará a função save_comment
, que ainda não definimos. Por fim, referenciamos o local-storage.py
, que conterá nosso código Python. Vamos criar o arquivo agora.
Crie local-storage.py
e adicione o seguinte:
from js import localStorage
def save_comment(e):
text = Element("comment").value
localStorage.setItem("comment", text)
if localStorage.getItem("comment"):
text_area = Element("comment")
text_area.write(localStorage.getItem("comment"))
Primeiro, importamos o localStorage
objeto do js
módulo. Em seguida, definimos a save_comment()
função, que recebe e
como parâmetro. Dentro da função, invocamos a Element
classe com o ID comment
para obter uma referência de área de texto. Uma vez que o método encontra a área de texto, usamos a value
propriedade para obter o conteúdo da área de texto e armazenar o valor na text
variável. Na próxima linha, invocamos o setItem()
método do localStorage
objeto para salvar o texto do comentário no localStorage
objeto sob a comment
chave.
Agora, a save_comment()
função só será executada quando o save
botão for clicado. No entanto, procedendo fora da save_comment()
função, as linhas que seguem a função serão executadas apenas durante o carregamento da página.
Quando a página é carregada pela primeira vez, usamos a if
instrução para verificar se o localStorage
objeto possui dados sob a comment
chave. Se true, referenciamos a área de texto usando a Element
classe e armazenamos sua instância na text_area
variável. Em seguida, invocamos o write()
método da text_area
instância para atualizar o conteúdo da área de texto com os dados do armazenamento local.
Verifique se o seu servidor está funcionando e visite http://0.0.0.0:8000/storage.html
. Digite o texto que desejar e clique no botão Salvar .
Em seguida, atualize a URL e você verá que a área de texto contém o texto que você salvou na visita inicial.
Com isso, agora você sabe como aproveitar o localStorage
uso do PyScript. Em seguida, leremos um arquivo no sistema de arquivos usando o PyScript.
Nesta seção, usaremos o PyScript para ler dados de um arquivo de texto simples no sistema de arquivos local e anexar seu conteúdo ao DOM.
Primeiro, vamos criar um arquivo contendo os dados que queremos ler. No diretório principal do projeto, execute o seguinte comando para criar e mover para um novo diretório:
mkdir data && cd data
Em seguida, crie um names.txt
arquivo e adicione o seguinte conteúdo, que são nomes de frameworks da web Python:
Django
Flask
FastAPI
web2p
Salve o arquivo e volte para a raiz do diretório do seu projeto:
cd ..
Com o arquivo criado, crie um file-system.html
arquivo em seu editor de texto com o seguinte:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Read data from file system</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<py-env>
- paths:
- /data/names.txt
</py-env>
<ul id="frameworks">
</ul>
<py-script src="./read-file.py"></py-script>
</body>
</html>
Na <py-env>
tag, especificamos o caminho para o names.txt
, que é relativo ao file-system.html
caminho. Em seguida, criamos uma <ul>
tag vazia com um frameworks
ID. Por fim, referenciamos o read-file.py
, que definiremos em breve.
Crie um read-file.py
com o seguinte conteúdo:
ul_element = document.querySelector("#frameworks")
with open("names.txt") as f:
for line in f:
li_element = document.createElement("li")
li_element.innerText = line
ul_element.appendChild(li_element)
Na primeira linha, invocamos o querySelector()
método com um seletor de ID #frameworks
, que obtém uma referência do <ul>
elemento. Na segunda linha, chamamos o open()
método com o nome do arquivo names.txt
e armazenamos o objeto arquivo como f
.
Dentro da with
instrução, iteramos sobre cada linha armazenada no objeto de arquivo f
. Durante cada iteração, criamos um <li>
elemento usando o método document
do objeto createElement()
. Em seguida, definimos o <li>
conteúdo do texto para o valor na line
variável usando a innerText
propriedade da li_element
instância. Finalmente, acrescentamos o <li>
elemento ao <ul>
elemento chamando the appendChild()
com li_element
o argumento.
Inicie o servidor novamente (se você o parou antes):
python -m http.server
Visite o http://0.0.0.0:8000/file-system.html
URL e você verá que o conteúdo do arquivo de texto simples é exibido na página:
Se você inspecionar os elementos, verá que há quatro <li>
elementos que foram anexados ao <ul>
elemento.
Com isso, agora você pode ler arquivos no sistema de arquivos. Você pode usar a mesma abordagem para ler arquivos CSV e muitos outros formatos de arquivo.
Neste tutorial, aprendemos como usar o PyScript REPL, criar módulos personalizados, usar módulos da biblioteca padrão do Python e importar módulos de terceiros. Também aprendemos como acessar e manipular elementos usando PyScript, fazer solicitações de API, usar localStorage
e ler um arquivo de texto simples do sistema de arquivos.
Para explorar mais o PyScript, visite a página inicial do PyScript . Além disso, consulte a página de documentação do Pyodide para saber mais sobre as possibilidades que ele permite no navegador.
Fonte: https://blog.logrocket.com/pyscript-run-python-browser/
1659428160
Trong một thời gian dài, JavaScript đã là ngôn ngữ thống trị trong việc phát triển giao diện người dùng do khả năng chạy nguyên bản trong trình duyệt và tương tác với HTML và CSS thông qua API DOM. Với sự ra đời của WebAssembly, mọi thứ bắt đầu thay đổi từ từ. Các ngôn ngữ như Go, Rust, C, C ++ và nhiều ngôn ngữ khác hiện có thể chạy trong trình duyệt với tốc độ gần như nguyên bản và Python đã không bị bỏ lại phía sau.
Với sự ra đời của PyScript, các nhà phát triển giao diện người dùng giờ đây có thể xây dựng giao diện người dùng phong phú với Python. Hơn nữa, họ cũng có thể khai thác hệ sinh thái Python, có các mô-đun khoa học hữu ích như NumPy , Matplotlib , v.v.
Để tận dụng tối đa hướng dẫn này, bạn sẽ cần:
PyScript là một khung công tác web mã nguồn mở cho phép bạn tạo các ứng dụng web giao diện người dùng bằng Python. Với PyScript, bạn có thể nhúng mã Python vào HTML hoặc liên kết đến tệp Python và mã sẽ thực thi trong trình duyệt - mà không cần chạy Python trong chương trình phụ trợ.
PyScript được tạo ra bởi Anaconda và được công bố công khai vào ngày 30 tháng 4 tại PyCon US 2022. Tại thời điểm viết bài này, PyScript đang ở trạng thái alpha và đang tích cực được phát triển, vì vậy dự kiến sẽ có những thay đổi đột phá và các tính năng mới hơn vì nó chưa đã được phát hành ổn định.
PyScript được xây dựng dựa trên Pyodide , chuyển CPython sang WebAssembly. WebAssembly là một định dạng nhị phân cấp thấp cho phép bạn viết chương trình bằng các ngôn ngữ khác, sau đó được thực thi trong trình duyệt. Với CPython trong WebAss ...
Trước khi bắt đầu sử dụng PyScript, hãy tạo thư mục chứa mã của chúng ta.
Để làm điều đó, hãy mở thiết bị đầu cuối của bạn và tạo thư mục dự án bằng mkdir
lệnh ở vị trí bạn chọn:
mkdir pyscript_demo
Tiếp theo, di chuyển vào thư mục bạn vừa tạo bằng cd
lệnh:
cd pyscript_demo
Thông thường, các nhà phát triển giao diện người dùng sử dụng các công cụ định dạng tự động như Prettier trong trình soạn thảo văn bản của họ để định dạng mã khi lưu. Mặc dù điều này hoạt động tốt cho HTML, CSS và JavaScript, điều này có thể gây ra sự cố trong mã Python vì Python nghiêm ngặt về thụt lề.
Hiện tại, các công cụ định dạng tự động như Prettier không nhận dạng được cú pháp PyScript, cú pháp mới được khoảng hai tháng kể từ khi viết bài này. Các công cụ này tự động định dạng mã Python như JavaScript, giúp phá vỡ thụt lề mã. Để khắc phục điều này, chúng tôi sẽ tắt tính năng tự động định dạng cho thư mục này ngay bây giờ.
Giả sử bạn đang sử dụng VSCode, chúng tôi có thể tắt tính năng tự động định dạng như sau.
Trong thư mục dự án của bạn, hãy tạo một .vscode
thư mục và điều hướng vào thư mục bằng lệnh sau.
mkdir .vscode && cd .vscode
Tiếp theo, tạo một settings.json
tệp và thêm các nội dung sau:
{
"editor.formatOnSave": false
}
Cùng với đó, tính năng tự động định dạng khi lưu cho thư mục này đã bị tắt trong VSCode và bây giờ chúng tôi đã sẵn sàng để bắt đầu sử dụng PyScript.
Bây giờ thư mục của chúng tôi đã được thiết lập cho PyScript, trước tiên chúng tôi sẽ thêm các liên kết đến nội dung PyScript bao gồm tệp CSS và tệp JavaScript trong <head>
phần của trang HTML.
Khi nội dung đã được thêm, bạn có thể sử dụng PyScript trong tệp HTML theo một trong hai cách:
<py-script>
thẻ trong tệp HTML. Thẻ <py-script>
có thể được thêm vào thẻ <head>
hoặc <body>
tùy thuộc vào nhiệm vụ của bạn trong tay.py
phần mở rộng, sau đó bạn có thể tham chiếu trong <py-script>
thẻ bằng cách sử dụng src
thuộc tínhCách dễ nhất và nhanh nhất để bắt đầu sử dụng PyScript là nhúng mã Python vào tệp HTML. Hãy làm điều đó!
Mở trình soạn thảo văn bản ưa thích của bạn, tạo hello-world.html
tệp và thêm các nội dung sau:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Hello World!</title>
<!-- linking to PyScript assets -->
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<!-- Put Python code inside the the <py-script> tag -->
<py-script>print("Hello World!")</py-script>
</body>
</html>
Trong <head>
phần này, chúng tôi liên kết đến pyscript.css
tệp, chứa các kiểu cho các thành phần trực quan PyScript, REPL, trình tải PyScript, v.v. Sau đó, chúng tôi liên kết đến pyscript.js
tệp, tệp này thiết lập các tính năng cần thiết để sử dụng PyScript, chẳng hạn như tạo các thẻ như <py-script>
nơi bạn có thể viết mã Python của mình.
Trong <body>
thẻ, bạn nhúng mã Python vào <py-script>
thẻ. Hiện tại, chúng tôi đang giữ mọi thứ đơn giản, vì vậy chúng tôi chỉ in Hello World
cho người dùng.
Đảm bảo lưu tệp của bạn trong thư mục gốc của thư mục dự án và mở hello-world.html
tệp trong Chrome. Sẽ mất vài giây để tải và khi trang đã được tải xong, nó sẽ trông giống như sau:
Trong khi đặt mã Python trong <py-script>
thẻ hoạt động, một cách tiếp cận tốt hơn và có thể mở rộng hơn nhiều là thêm mã vào tệp bên ngoài và tham chiếu nó trong tệp HTML khi bạn tạo nhiều trang HTML hơn hoặc tập lệnh của bạn lớn hơn.
Sau đây là một số lý do tại sao bạn nên xem xét sử dụng mã PyScript trong một tệp bên ngoài:
Để sử dụng PyScript bên ngoài, chúng tôi sẽ tạo một index.html
tệp, một tệp Python kết thúc bằng .py
phần mở rộng chứa mã Python của chúng tôi và cuối cùng tham chiếu tệp Python trong index.html
tệp.
index.html
tệpTạo index.html
tệp và liên kết đến nội dung PyScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Greetings!</title>
<!-- linking to PyScript assets -->
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
</body>
</html>
Tệp không hoạt động nhiều; chúng tôi chỉ đang liên kết đến các tài nguyên PyScript. Để làm cho nó hữu ích hơn, chúng tôi sẽ tạo một main.py
tệp nơi mã Python của chúng tôi sẽ cư trú.
main.py
tệpHãy tạo một hàm Python để in một tin nhắn chào mừng.
Trong trình soạn thảo văn bản của bạn, hãy tạo main.py
tệp và thêm mã bên dưới:
def greetings(name):
print(f'Hi, {name}')
greetings('John Doe')
Hàm greetings()
nhận một name
tham số và in ra một thông điệp chào mừng với tên được lưu trong name
tham số. Khi chúng ta gọi greetings()
hàm với John Doe
như một đối số, nó sẽ in ra hi, John Doe
.
main.py
tệp trong tệp HTMLBây giờ bạn đã tạo mã Python, bạn sẽ tham chiếu đến main.py
tệp trong index.html
tệp.
Mở index.html
và thêm dòng bên trong <body>
thẻ:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Greetings!</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
// add the following line
<py-script src="./main.py"></py-script>
</body>
</html>
Thẻ <py-script>
có một src
thẻ, thẻ này chấp nhận đường dẫn tệp của tệp Python.
index.html
tệp trong trình duyệtBây giờ mọi thứ đã sẵn sàng, chúng tôi sẽ mở index.html
trong trình duyệt.
Tuy nhiên, các trình duyệt sẽ từ chối tải và thực thi tệp Python bên ngoài do lỗi chính sách Chia sẻ Tài nguyên Nhiều Nguồn gốc (CORS) . Để giải quyết vấn đề này, chúng ta sẽ cần sử dụng một máy chủ. Điều tốt là Python đi kèm với một máy chủ web mà chúng ta có thể sử dụng! Máy chủ không cần được tạo bằng Python, bạn có thể sử dụng máy chủ trực tiếp hoặc bất kỳ máy chủ nào bạn chọn.
Để tạo một máy chủ, hãy mở thiết bị đầu cuối trong thư mục gốc của dự án của bạn và chạy lệnh sau:
python -m http.server
Tiếp theo, mở Chrome và truy cập http://0.0.0.0:8000/
. Máy chủ sẽ tự động tải index.html
tệp và bạn sẽ thấy như sau:
Đối với phần còn lại của hướng dẫn này, chúng tôi sẽ tham chiếu đến một tệp Python bên ngoài, tệp này sẽ yêu cầu chúng tôi sử dụng máy chủ để tránh lỗi CORS và đôi khi chúng tôi sẽ nhúng mã Python vào HTML vì mục đích ngắn gọn.
PyScript đi kèm với Vòng lặp Đọc-Đánh giá-In (REPL), bạn có thể sử dụng để thử nghiệm và thử mã Python.
Để sử dụng REPL, hãy thêm <py-repl>
thẻ vào <body>
thẻ trong index.html
tệp của bạn:
<!DOCTYPE html>
...
<body>
<py-script src="./main.py"></py-script>
// add the following tag
<py-repl></py-repl>
</body>
</html>
Với máy chủ vẫn đang chạy, hãy truy cập http://0.0.0.0:8000/
. Bạn sẽ thấy một phần mới, nơi bạn có thể nhập mã Python.
Bạn có thể nhập mô-đun, đánh giá biểu thức, tạo hàm và làm nhiều việc khác. Để xem biểu thức được đánh giá là gì, bạn cần nhấp vào biểu tượng Phát màu xanh lục .
Hình ảnh sau đây cho thấy một số thao tác bạn có thể thực hiện:
Bây giờ chúng ta đã biết cách sử dụng REPL, tiếp theo chúng ta sẽ học cách tạo và sử dụng các mô-đun trong PyScript.
Trong phần này, chúng tôi sẽ tạo một mô-đun Python tùy chỉnh và sử dụng nó trong mã của chúng tôi. Chúng tôi cũng sẽ sử dụng các mô-đun từ thư viện chuẩn Python, cũng như các mô-đun của bên thứ ba.
Để sử dụng mô-đun, chúng tôi sẽ giới thiệu một thẻ mới, <py-env>
cho phép chúng tôi tham chiếu đến mô-đun hoặc đường dẫn tệp mô-đun.
Hãy tạo một mô-đun cục bộ chứa hai chức năng.
Tạo một mathslib.py
tệp trong thư mục dự án của bạn và thêm mã bên dưới:
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
Ở đây chúng tôi đã tạo ra hai hàm thực hiện các phép toán cộng và trừ.
Tiếp theo, tạo một modules.html
tệp và thêm các nội dung sau:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>local modules</title>
<!-- linking to PyScript assets -->
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<py-env>
- paths:
- mathslib.py
</py-env>
<py-script>
from mathslib import subtract
print(subtract(8, 4))
<py-script>
</body>
</html>
Trong <body>
thẻ, chúng tôi sử dụng <py-env>
thẻ, thẻ này chấp nhận danh sách YAML có paths
làm khóa của nó. Đây mathslib.py
là đường dẫn tệp của mô-đun tùy chỉnh liên quan đến modules.html
tệp. Khi đường dẫn đến mô-đun tùy chỉnh được chỉ định, PyScript sẽ nhập mô-đun trong tệp.
Với mô-đun được tải, trong <py-script>
thẻ, chúng tôi nhập subtract()
hàm từ mathslib.py
và gọi hàm với các đối số 8
và 4
.
Khi máy chủ đang chạy, hãy truy cập http://0.0.0.0:8000/modules.html
và bạn sẽ thấy một trang tương tự như sau:
PyScript, với sự trợ giúp của Pyodide, cung cấp quyền truy cập vào rất nhiều mô-đun có sẵn trong thư viện chuẩn Python sẵn sàng cho bạn sử dụng, ngoại trừ những điều sau:
Truy cập tài liệu Pyodide để xem danh sách toàn diện. Ngoài ra, hãy lưu ý đến các mô-đun được bao gồm nhưng không có chức năng, chẳng hạn như mô-đun đa xử lý, phân luồng và ổ cắm.
Các mô-đun trong thư viện chuẩn có sẵn trong không gian tên PyScript theo mặc định; bạn chỉ cần nhập chúng để sử dụng chúng trong tệp.
Vẫn trong modules.html
tệp, hãy sửa đổi mã Python trong <py-script>
thẻ để tạo một số ngẫu nhiên bằng cách sử dụng random
mô-đun:
from mathslib import subtract
import random
print(subtract(8, 4))
print("random number generated: ")
print(random.randint(1, 12))
Bây giờ hãy truy cập http://0.0.0.0:8000/modules.html
trang và bạn sẽ thấy một số ngẫu nhiên được tạo mỗi khi bạn làm mới trang:
Ngoài việc sử dụng các mô-đun Python có sẵn, bạn cũng có thể sử dụng các thư viện của bên thứ ba được vận chuyển trong Pyodide, chẳng hạn như:
Để có danh sách đầy đủ các gói của bên thứ ba được hỗ trợ, hãy truy cập tài liệu Pyodide hoặc theo dõi kỹ repo Pyodide GitHub .
Để thêm gói của bên thứ ba, hãy tạo một tệp HTML mới third-party.html
và thêm mã sau:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>local modules</title>
<!-- linking to PyScript assets -->
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<!-- thirdparty dependencies added here -->
<py-env>
- numpy
- matplotlib
</py-env>
<py-script>
import numpy as np
import matplotlib.pyplot as plt
arr = np.array([1, 2, 3, 4, 5])
plt.plot(arr)
plt
<py-script>
</body>
</html>
Trong <py-env>
thẻ, chúng tôi thêm danh sách các gói của bên thứ ba mà chúng tôi muốn sử dụng trong dự án của mình, đó là các gói NumPy và Matplotlib. Tiếp theo, trong <py-script>
thẻ, chúng tôi nhập NumPy dưới dạng np
và Matplotlib dưới dạng plt
. Sau đó, chúng tôi gọi phương thức của NumPy, array
phương thức này tạo ra một mảng sau đó được lưu trữ trong arr
biến. Sau đó, chúng ta gọi phương thức của Matplotlib plot
với mảng arr
là đối số để vẽ đồ thị.
Đảm bảo rằng tệp của bạn đã được lưu và truy cập http://0.0.0.0:8000/third-party.html
trang. Bạn sẽ thấy một biểu đồ tương tự như sau:
Bây giờ bạn đã hiểu cách sử dụng các mô-đun tùy chỉnh, có sẵn và các gói của bên thứ ba, chúng ta sẽ tìm hiểu cách truy cập và thao tác với các phần tử HTML trong phần tiếp theo.
Trong phần này, chúng ta sẽ tìm hiểu cách chọn một phần tử HTML bằng cách sử dụng ID hoặc một lớp CSS, sửa đổi một phần tử, đính kèm các sự kiện vào một phần tử và tạo các phần tử mới bằng PyScript.
Element
lớp họcPyScript đi kèm với Element
lớp, cho phép bạn chọn một phần tử HTML bằng cách sử dụng ID của nó.
Để xem nó hoạt động như thế nào, hãy tạo một elements.html
tệp và chèn các nội dung sau:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Element class</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<ul id="navigation">
<li class="home">home</li>
<li class="about">about</li>
<li class="services">services</li>
<li class="contact">contact</li></ul>
</div>
<div id="output"></div>
<py-script src="./access-elements.py"></py-script>
</body>
</html>
Trong <body>
thẻ, chúng tôi có một <ul>
phần tử có ID là navigation
. Chúng tôi sẽ sử dụng ID để chọn phần tử này bằng cách sử dụng Element
lớp. Cá thể được chọn sẽ cung cấp cho chúng ta các phương thức mà chúng ta có thể sử dụng để chọn các phần tử con và thao tác với chúng.
Một thẻ khác mà chúng tôi sẽ sử dụng là thẻ <div>
có ID là output
. Chúng tôi sẽ sửa đổi nó innerHTML
để viết một giá trị mới. Cuối cùng, sau <div>
thẻ, chúng tôi liên kết đến access-elements.py
tệp sẽ chứa mã Python của chúng tôi. Nó chưa tồn tại, vì vậy hãy tiếp tục và tạo ra nó.
Sau khi bạn tạo access-elements.py
tệp, hãy thêm mã sau vào tệp:
ul_element = Element("navigation")
first_element = ul_element.select('.home').add_class('first')
second_element = ul_element.select('.about').remove_class('about')
div_element = Element("output")
div_element.write("Value set from PyScript")
Trong đoạn mã trước, chúng tôi sử dụng Element
lớp để truy cập <ul>
phần tử bằng navigation
ID.
Khi một phần tử được chọn bằng cách sử dụng Element
lớp, bạn có thể tận dụng một số phương pháp sau:
write()
: Đặt innerHTML
giá trịselect()
: Sử dụng bộ chọn CSS để tìm các phần tử conadd_class()
: Thêm một hoặc nhiều lớp vào một phần tửremove_class()
: Loại bỏ một hoặc nhiều lớp khỏi một phần tửTrong dòng thứ hai, chúng tôi sử dụng select()
phương thức để chọn phần tử con đầu tiên của <ul>
phần tử bằng cách sử dụng tên lớp của nó home
,. Sau khi chọn con, chúng ta gọi add_class()
phương thức để thêm một lớp mới first
vào <li>
phần tử.
Trong dòng thứ ba, chúng tôi truy cập phần tử con thứ hai bằng tên lớp của nó about
, sau đó loại bỏ lớp của nó about
bằng remove_class()
phương thức.
Tiếp theo, chúng ta gọi Element
lớp có ID output
, lớp này cung cấp một tham chiếu đến <div>
phần tử nằm sau ul
phần tử trong elements.html
tệp. Cuối cùng, chúng tôi gọi write()
phương thức với chuỗi Value set from PyScript
. Phương thức sẽ đặt giá trị <div>
phần tử innerHTML
thành đối số chuỗi.
Với máy chủ vẫn hoạt động, hãy truy cập http://0.0.0.0:8000/elements.html
và kiểm tra <ul>
phần tử. Bạn sẽ thấy <li>
phần tử đầu tiên bây giờ có thêm một lớp ( first
), phần tử thứ hai không có lớp và div
phần tử bây giờ có văn bản mà chúng tôi đặt bằng Python.
Bây giờ chúng ta có thể chọn các phần tử HTML và thực hiện một số thao tác cơ bản. Trong phần này, chúng tôi sẽ đính kèm một sự kiện nhấp chuột vào một phần tử và để mã Python thực thi khi phần tử đã được nhấp vào.
Tạo một events.html
tệp và viết mã bên dưới:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Adding Events</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<button id="click-btn" class="bg-blue-500 text-white" pys-onClick="handle_click">Click</button>
<div id="output"></div>
<py-script src="./event-handlers.py"></py-script>
</body>
</html>
Trong <body>
thẻ, chúng ta có <button>
một class
thuộc tính có chứa một số lớp là một phần của pyscript.css
tệp. Thẻ <button>
cũng có một pys-onclick
thuộc tính gắn một click
sự kiện vào nút. Thuộc pys-onclick
tính chấp nhận tên hàm handle_click
, sẽ là hàm chạy khi nút được nhấp.
Tiếp theo, chúng ta có div
phần tử có ID là output
. Chúng tôi sẽ sửa đổi phần tử trong innerHTML
với handle_click
chức năng chúng tôi xác định.
Cuối cùng, chúng tôi liên kết đến event-handlers.py
tệp, tệp này sẽ chứa hàm xử lý sự kiện.
Hãy xác định event-handlers.py
và thêm những điều sau:
def handle_click(e):
pyscript.write("output", "you clicked the button")
Hàm handle_click
có một tham số, e
là một đối tượng sự kiện được truyền tự động vào hàm khi bạn nhấp vào nút. Bên trong hàm, chúng ta gọi phương thức của PyScript, write()
phương thức này nhận hai đối số: ID phần tử output
và giá trị mà chúng ta muốn viết, trong trường hợp của chúng ta you clicked the button
,.
Đảm bảo rằng máy chủ của bạn đang chạy:
python -m http.server
Sau đó, truy cập URL http://0.0.0.0:8000/events.html
trong Chrome. Khi trang tải, hãy nhấp vào nút và thông báo có nội dung “bạn đã nhấp vào nút” sẽ xuất hiện:
PyScript đi kèm với một js
mô-đun cho phép bạn truy cập vào các phương thức JavaScript, như ,, querySelector()
v.v. , để truy cập và thao tác các phần tử HTML. Với những thứ này, bạn sẽ có thể kết hợp JavaScript và Python để thực hiện một số thao tác DOM thú vị. Đây là một ví dụ:createElement()appendChild()
import js
print(js.window.innerHeight)
nav = js.document.createElement("div")
js.document.body.prepend(nav)
js.console.log("nav element created")
Như bạn có thể thấy, chúng tôi đang trộn các phương thức mã Python như print()
cùng với JavaScript window
hoặc document
thuộc tính.
Trong phần này, chúng ta sẽ chủ yếu tập trung vào document
các phương thức và thuận tiện, PyScript tự động cung cấp nó trong phạm vi Python. Chúng tôi thậm chí sẽ không cần nhập js
mô-đun để sử dụng các document
phương pháp.
Tạo dom.html
tệp và thêm mã sau:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Mixing JavaScript and Python</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<ul id="navigation">
</ul>
<py-script src="./js-dom.py"></py-script>
</body>
</html>
Trong <body>
thẻ, chúng tôi chỉ có một <ul>
phần tử trống có ID là navigation
. Tiếp theo, chúng tôi tham chiếu đến js-dom.py
sẽ chứa mã Python của chúng tôi.
Tạo js-dom.py
tệp và thêm các nội dung sau:
nav_parent = document.querySelector('#navigation')
nav_texts = ["home", "about", "services", "contact"]
for text in nav_texts:
nav_item = document.createElement("li")
nav_item.textContent = text
nav_item.className = "nav_element"
nav_parent.appendChild(nav_item)
Trong dòng đầu tiên, chúng tôi gọi querySelector()
phương thức của document
mô-đun với #navigation
làm đối số của nó. Phương thức sẽ tìm và trả về một phần tử có ID navigation
là <ul>
phần tử trong dom.html
tệp.
Trong dòng thứ hai, chúng tôi tạo một danh sách văn bản điều hướng và lưu trữ nó trong nav_texts
biến. Sau đó, chúng tôi lặp lại nav_texts
danh sách. Trên mỗi lần lặp, chúng tôi gọi createElement()
phương thức bằng một chuỗi li
để tạo một <li>
phần tử.
Sau đó, chúng tôi thêm văn bản vào <li>
phần tử bằng cách sử dụng thuộc textContent
tính và thêm tên lớp nav_element
vào <li>
phần tử sử dụng thuộc className
tính. Cuối cùng, chúng ta nối <li>
phần tử vào <ul>
phần tử bằng cách gọi phần tử appendChild()
với nav_item
phần tử là đối số.
Đảm bảo rằng tệp của bạn đã được lưu và máy chủ vẫn đang chạy. Hãy truy cập http://0.0.0.0:8000/dom.html
và bạn sẽ thấy một trang giống như sau:
Nếu bạn đào sâu hơn và kiểm tra các phần tử, bạn sẽ thấy rằng các <li>
phần tử đã được tạo với tên lớp nav_element
, chúng tôi đặt bằng Python:
Bây giờ chúng ta có thể truy cập và thao tác DOM bằng cách sử dụng Element
lớp, đính kèm các sự kiện vào các phần tử và sử dụng JavaScript để truy vấn và sửa đổi DOM. Tiếp theo, chúng tôi sẽ tìm nạp dữ liệu từ một API bằng PyScript.
Trong phần này, chúng tôi sẽ sử dụng PyScript để gửi GET
yêu cầu đến một API để lấy dữ liệu. API chúng tôi sẽ sử dụng là API dữ liệu ngẫu nhiên . Chúng tôi sẽ tạo một nút với sự kiện nhấp chuột chạy một chức năng gọi API mỗi khi nút được nhấp.
Tạo một fetch_data.html
tệp trong thư mục của bạn và thêm các nội dung sau:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Fetch data from API</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<button id="get-name" class="bg-green-600 text-white" pys-onClick="get_random_name">Generate Random Name</button>
<div id="output"></div>
<py-script src="./fetch.py"></py-script>
</body>
</html>
Mã sẽ quen thuộc vào thời điểm này. Phần quan trọng nhất là <button>
thẻ, có pys-onClick
thuộc tính chấp nhận get_random_name()
hàm. Hàm sẽ nằm trong fetch.py
tệp được liên kết ở dưới cùng. Hãy tiếp tục và tạo tệp.
Trong trình soạn thảo văn bản của bạn, hãy tạo một tệp mới có tên fetch.py
với nội dung sau:
from pyodide.http import pyfetch
import asyncio
async def get_random_name(e):
response = await pyfetch(url="https://random-data-api.com/api/name/random_name", method="GET")
data = await response.json()
first_name = data.get('first_name')
middle_name = data.get('middle_name')
last_name = data.get('last_name')
output = f"Random name: {first_name} {middle_name} {last_name}"
pyscript.write('output', output)
Trong dòng đầu tiên, chúng tôi nhập pyfetch()
phương thức từ pyodide.http
mô-đun, cho phép chúng tôi thực hiện các yêu cầu mạng không đồng bộ. Trong dòng thứ hai, chúng tôi nhập asyncio
mô-đun, là một phần của thư viện chuẩn Python và cung cấp các từ khóa async
và await
hữu ích để tạo các hàm không đồng bộ.
Tiếp theo, chúng tôi xác định một hàm không đồng bộ get_random_name()
bằng cách đặt tiền tố cho nó với async
từ khóa từ asyncio
mô-đun. Trong hàm, chúng tôi gọi pyfetch()
phương thức chấp nhận hai đối số:
URL
: Điểm cuối APImethod
: Chỉ định phương thức HTTP mà bạn muốn sử dụng, đây là GET
phương thức ở đây.Khi pyfetch()
chạy, nó trả về một đối tượng, đối tượng này sau đó được lưu trữ trong response
biến. Trong dòng tiếp theo, chúng tôi gọi đối tượng json()
on response
để phân tích cú pháp JSON và trả về một từ điển Python, sau đó được lưu trữ trong data
biến.
Trong vài dòng tiếp theo, bạn trích xuất họ, tên đệm và họ từ data
dict và lưu trữ chúng trong các biến tương ứng. Cuối cùng, chúng tôi nối các tên bằng cách sử dụng chuỗi f của Python và gọi pyscript.write()
phương thức để ghi dữ liệu trong <div>
phần tử có ID là output
.
Đảm bảo rằng máy chủ của bạn đang chạy và truy cập http://0.0.0.0:8000/fetch_data.html
trang. Sau khi tải trang, hãy nhấp vào Generate Random Name
nút. Bạn sẽ thấy rằng một tên mới được tạo ra mỗi khi nút được nhấp vào:
localStorage
Trong phần này, chúng tôi sẽ sử dụng bộ nhớ cục bộ để lưu và truy xuất dữ liệu. Bộ nhớ cục bộ là một đối tượng trong trình duyệt web có thể lưu trữ dữ liệu mà không có ngày hết hạn. Python có thể sử dụng bộ nhớ cục bộ bằng cách nhập nó từ js
mô-đun.
Để sử dụng bộ nhớ cục bộ, chúng tôi sẽ tạo một vùng văn bản cho phép người dùng nhập nhận xét. Nếu họ muốn lưu nhận xét, họ sẽ nhấp vào một save
nút sẽ chạy một chức năng lưu dữ liệu trong bộ nhớ cục bộ. Mỗi khi trang được truy cập, dữ liệu sẽ được truy xuất từ bộ nhớ cục bộ và vùng văn bản sẽ được đặt thành dữ liệu.
Tạo một storage.html
tệp và thêm các nội dung sau:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Store data in local storage</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<textarea id="comment" class="block border"></textarea>
<button id="save" class="bg-green-600 text-white"
pys-onClick="save_comment">Save</button>
<py-script src="./local-storage.py"></py-script>
</body>
</html>
Trong <body>
thẻ, chúng tôi tạo <textarea>
thẻ có ID comment
. Chúng tôi sẽ sử dụng ID này để lấy tham chiếu của phần tử vùng văn bản trong Python. Tiếp theo, chúng ta có một nút save
làm ID của nó và một sự kiện nhấp chuột sẽ gọi hàm save_comment
mà chúng ta chưa xác định. Cuối cùng, chúng tôi tham chiếu đến local-storage.py
, sẽ chứa mã Python của chúng tôi. Hãy tạo tệp ngay bây giờ.
Tạo local-storage.py
và thêm những thứ sau:
from js import localStorage
def save_comment(e):
text = Element("comment").value
localStorage.setItem("comment", text)
if localStorage.getItem("comment"):
text_area = Element("comment")
text_area.write(localStorage.getItem("comment"))
Đầu tiên, chúng tôi nhập localStorage
đối tượng từ js
mô-đun. Tiếp theo, chúng tôi xác định save_comment()
hàm, lấy e
làm tham số. Bên trong hàm, chúng ta gọi Element
lớp có ID comment
để lấy một tham chiếu của vùng văn bản. Khi phương thức tìm thấy vùng văn bản, chúng tôi sử dụng thuộc value
tính để lấy nội dung vùng văn bản và lưu trữ giá trị trong text
biến. Trong dòng tiếp theo, chúng tôi gọi setItem()
phương thức của localStorage
đối tượng để lưu văn bản nhận xét trong localStorage
đối tượng dưới comment
khóa.
Bây giờ, save_comment()
chức năng sẽ chỉ chạy khi save
nút được nhấp. Tuy nhiên, tiếp tục bên ngoài save_comment()
hàm, các dòng theo sau hàm sẽ chỉ thực thi trong quá trình tải trang.
Khi trang được tải lần đầu tiên, chúng tôi sử dụng if
câu lệnh để kiểm tra xem localStorage
đối tượng có dữ liệu dưới comment
khóa hay không. Nếu đúng, chúng tôi tham chiếu vùng văn bản bằng cách sử dụng Element
lớp và lưu trữ thể hiện của nó trong text_area
biến. Tiếp theo, chúng ta gọi write()
phương thức của text_area
instance để cập nhật nội dung vùng văn bản với dữ liệu từ bộ nhớ cục bộ.
Đảm bảo rằng máy chủ của bạn đang chạy và truy cập http://0.0.0.0:8000/storage.html
. Nhập bất kỳ văn bản nào bạn thích và nhấp vào nút Lưu .
Tiếp theo, làm mới URL và bạn sẽ thấy vùng văn bản chứa văn bản bạn đã lưu trong lần truy cập đầu tiên.
Với điều đó, bây giờ bạn biết cách tận localStorage
dụng bằng PyScript. Tiếp theo, chúng ta sẽ đọc một tệp trong hệ thống tệp bằng PyScript.
Trong phần này, chúng tôi sẽ sử dụng PyScript để đọc dữ liệu từ tệp plaintext trong hệ thống tệp cục bộ và nối nội dung của nó vào DOM.
Đầu tiên, hãy tạo một tệp chứa dữ liệu mà chúng ta muốn đọc. Trong thư mục dự án chính của bạn, hãy chạy lệnh sau để tạo và chuyển vào một thư mục mới:
mkdir data && cd data
Tiếp theo, tạo một names.txt
tệp và thêm các nội dung sau, là tên của các khuôn khổ web Python:
Django
Flask
FastAPI
web2p
Lưu tệp và quay lại thư mục gốc của thư mục dự án của bạn:
cd ..
Với tệp đã tạo, hãy tạo file-system.html
tệp trong trình soạn thảo văn bản của bạn với những điều sau:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Read data from file system</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<py-env>
- paths:
- /data/names.txt
</py-env>
<ul id="frameworks">
</ul>
<py-script src="./read-file.py"></py-script>
</body>
</html>
Trong <py-env>
thẻ, chúng tôi chỉ định đường dẫn đến names.txt
, có liên quan đến file-system.html
đường dẫn. Tiếp theo, chúng tôi tạo một <ul>
thẻ trống có frameworks
ID. Cuối cùng, chúng tôi tham khảo read-file.py
, mà chúng tôi sẽ xác định sớm.
Tạo một read-file.py
với các nội dung sau:
ul_element = document.querySelector("#frameworks")
with open("names.txt") as f:
for line in f:
li_element = document.createElement("li")
li_element.innerText = line
ul_element.appendChild(li_element)
Trong dòng đầu tiên, chúng tôi gọi querySelector()
phương thức với một bộ chọn ID #frameworks
, bộ chọn này sẽ nhận được một tham chiếu của <ul>
phần tử. Trong dòng thứ hai, chúng tôi gọi open()
phương thức với tên tệp names.txt
và lưu trữ đối tượng tệp dưới dạng f
.
Trong with
câu lệnh, chúng tôi lặp qua từng dòng được lưu trữ trong đối tượng tệp f
. Trong mỗi lần lặp, chúng tôi tạo một <li>
phần tử bằng phương thức document
của đối tượng createElement()
. Tiếp theo, chúng tôi đặt <li>
nội dung văn bản thành giá trị trong line
biến bằng cách sử dụng thuộc innerText
tính của li_element
cá thể. Cuối cùng, chúng tôi nối <li>
phần tử vào <ul>
phần tử bằng cách gọi đối số appendChild()
với the li_element
as.
Khởi động lại máy chủ (nếu bạn đã dừng trước đó):
python -m http.server
Truy cập http://0.0.0.0:8000/file-system.html
URL và bạn sẽ thấy nội dung từ tệp bản rõ được hiển thị trên trang:
Nếu bạn kiểm tra các phần tử, bạn sẽ thấy rằng có bốn <li>
phần tử đã được thêm vào <ul>
phần tử.
Với điều đó, bây giờ bạn có thể đọc các tệp trong hệ thống tệp. Bạn có thể sử dụng phương pháp tương tự để đọc tệp CSV và nhiều định dạng tệp khác.
Trong hướng dẫn này, chúng tôi đã học cách sử dụng PyScript REPL, tạo các mô-đun tùy chỉnh, sử dụng các mô-đun từ thư viện chuẩn Python và nhập các mô-đun của bên thứ ba. Chúng tôi cũng đã học cách truy cập và thao tác các phần tử bằng PyScript, thực hiện các yêu cầu API, sử dụng localStorage
và đọc tệp bản rõ từ hệ thống tệp.
Để khám phá thêm về PyScript, hãy truy cập trang chủ PyScript . Ngoài ra, hãy xem trang tài liệu Pyodide để tìm hiểu thêm về các khả năng mà nó cho phép trong trình duyệt.
Nguồn: https://blog.logrocket.com/pyscript-run-python-browser/
1649264700
El desarrollo de aplicaciones móviles multiplataforma le permite crear aplicaciones móviles para múltiples plataformas, como iOS y Android, con solo una pila de tecnología.
Esto significa que, en lugar de crear varias versiones de su aplicación, cada una escrita en el idioma nativo dedicado para cada plataforma, puede escribir su código una vez e implementarlo en varias plataformas a la vez.
Developer Experience (abreviado como DX) describe la experiencia que tienen los desarrolladores cuando usan bibliotecas de cliente, SDK, marcos, código fuente abierto, herramientas, API, tecnología o cualquier servicio.
DX comparte algunas ideas y filosofías del diseño de experiencia de usuario (UX).
La oportunidad de implementar una aplicación web con un solo comando de terminal es una indicación de lo que se puede percibir como una mejor experiencia del desarrollador, en lugar de seguir una larga lista de instrucciones para lograr los mismos resultados.
DX es uno de los factores latentes que impulsan a los desarrolladores a usar una herramienta y apegarse a ella.
Esta publicación compara el DX de algunos marcos móviles multiplataforma populares en función de cuatro factores que son realmente importantes para los desarrolladores:
Nuestra comparación se centrará en 5 marcos multiplataforma:
La configuración de un marco es su primera impresión. Comenzar fácilmente es lo que primero influye en DX sobre el flujo de trabajo del marco.
Aquí compararemos el proceso de configuración de los diferentes marcos móviles, sin tener en cuenta la configuración de Android Studio y/o XCode porque este es básicamente un paso obligatorio para todos ellos.
React Native : usando Expo , React Native es extremadamente fácil de comenzar.
Después de instalar NodeJS y Expo, solo tiene que escribir un solo comando y luego está listo para comenzar (sin instalar Android Studio o Xcode y suponiendo que tiene un dispositivo con la aplicación Expo instalada). La plantilla inicial se envía con una interfaz hermosa y simple para ayudar a guiar al desarrollador.
También puede iniciar una aplicación React Native sin Expo utilizando la herramienta de línea de comandos RN. Hacer que nuestra aplicación RN se ejecute con este método no es demasiado trabajo. La herramienta CLI ayuda a los desarrolladores a obtener su primera aplicación de pantalla lo suficientemente rápido.
Comenzar con RN solo se vuelve complicado cuando necesitamos integrarlo en una aplicación nativa existente o construir para plataformas fuera del árbol . Sin embargo, esto se considera una práctica avanzada y no debe tenerse en cuenta en esta comparación.
React Native ha estado haciendo su tarea tan bien que incluso lanzaron un react-native doctor
paquete para ayudar a verificar la configuración en su computadora.
Flutter : instalar Flutter SDK es tan fácil como instalar un paquete en su computadora. Su guía muestra cuatro pasos simples que son fáciles de seguir. Incluso si esto se vuelve un poco problemático para ti, Flutter te tiene cubierto.
Son bien conocidos por preocuparse mucho por DX. Integraron una herramienta llamada flutter doctor
en su CLI para ayudarlo a obtener información sobre lo que funciona bien y lo que podría no funcionar bien en la cadena de herramientas del marco.
Las herramientas de Flutter también deben configurarse en su editor de código para ayudar a proporcionar un mejor DX. Esto explica algunos pasos adicionales en la configuración. Estos pasos son opcionales, pero ayudaron a lograr las mejores reseñas de Flutter en Internet.
Todo lo de Flutter se siente "fuera de la caja". Es fácil crear una aplicación más compleja usando solo los paquetes que se enviaron con el SDK de Flutter.
Xamarin : si es un desarrollador de C# acostumbrado a Visual Studio IDE, instalar Xamarin seguramente le parecerá un paseo por el parque. Sin embargo, si no tiene Visual Studio, es posible que la instalación de VS2019 y las herramientas de Xamarin le resulten tediosas.
Una vez que instale Xamarin, puede iniciar una aplicación a través de la GUI de introducción de Visual Studio. Aquí simplemente selecciona la aplicación móvil y elige una plantilla inicial de las proporcionadas (Maestro-detalle, Tabulado, Shell y En blanco). Luego selecciona la plataforma, haz clic en continuar y espera a que se inicialice.
Ionic : Desde v1, Ionic siempre ha sido muy fácil para comenzar. Ahora estamos en v5 y se está volviendo aún más fácil.
Ocurre en 3 pasos: instalar Ionic con Node, ejecutar y seguir las indicaciones de ionic start myApp <template-name>
(donde le proporcionaron 3 plantillas: en blanco, pestañas y menú lateral), y finalmente ejecutar la aplicación con ionic serve
.
Aquí, la aplicación predeterminada se muestra en su navegador como un sitio web móvil, pero así es como se verá la aplicación después de las compilaciones.
También es muy importante tener en cuenta que Ionic tiene v5, un asistente de inicio hermoso e intuitivo que lo ayuda a obtener el mismo resultado que el anterior con solo una instrucción de línea de comando.
NativeScript : tienen dos formas de comenzar: configuración rápida y configuración completa. El proceso de configuración rápida es similar a React Native con Expo: hay una aplicación que descarga en el dispositivo físico y luego React Native se conecta a la terminal de desarrollo a través de un enlace y podemos comenzar a trabajar en nuestra aplicación (sin instalar Android Studio o XCode) .
La configuración completa también es fácil, ya que proporcionan enlaces que funcionan bien con la terminal de su sistema operativo para instalar el marco. Además, como Flutter, tienen una herramienta médica accesible con: tns doctor
, que verifica la configuración en su computadora.
Nota :
Cabe señalar que la mayoría de las configuraciones rápidas tienen algunas limitaciones con los flujos de trabajo. Por ejemplo, el acceso a algunos complementos nativos está restringido, las pruebas unitarias a veces son imposibles (en el caso de NativeScript) y algunos recursos (pantallas de presentación, íconos) no son accesibles.
Cualquier desarrollador puede admitir que enamorarse de una herramienta a veces pasa por la facilidad de trabajar con el manual de la herramienta.
React Native : aunque últimamente se han realizado algunas mejoras importantes en los documentos de React Native, lo más probable es que los desarrolladores de React Native tiendan a obtener un toque de temas avanzados de recursos como publicaciones de blogs, tutoriales en línea y cursos.
Esto parece estar relacionado con el hecho de que los temas de React Native que van desde el nivel medio hasta el avanzado exigen mucho más (administración de estado, navegación, animaciones y mucho más) de lo que propone su API central.
Flutter : los documentos de Flutter deben ser los más queridos de los cinco marcos. Lo inundaron con información organizada para ayudar a cualquiera a revisarlos. Desde comandos simples hasta libros de cocina que incluyen videos informativos breves y clases de widgets, la documentación de Flutter está muy bien presentada. ¿Mencioné que se puede acceder fácilmente a la API de referencias de clase del widget desde el código fuente de cada widget?
Xamarin : los desarrolladores de Xamarin dicen que sus documentos están "llenos", ¡lo cual es cierto! Xamarin tiene, entre los cinco, uno de esos documentos a los que siempre volverá cuando necesite información sobre cualquier tema del marco.
Puede pasar de principiante a avanzado únicamente con el material de los documentos. Su navegación es realmente intuitiva e incluye breves tutoriales y enlaces a temas abiertos sobre los temas y casos de uso.
Ionic : Está claro que Ionic hizo un trabajo asombroso en su documentación. En cada actualización importante, todo el sitio web cambia a favor de una mejor experiencia de usuario.
A la mayoría de los desarrolladores que trabajan con Ionic les resulta fácil buscar, encontrar e integrar los componentes que necesitan.
NativeScript : una cosa sobre NativeScript es que es mucho mejor que lo que anuncian. Los documentos de NativeScript son bastante básicos: necesitan más guías para mostrar a los desarrolladores lo fácil que es aprovechar el poder del marco.
Además, al intentar pasar de principiante a experimentado, creemos que los documentos de NativeScript carecen de algunos ejemplos claros de lo que el marco realmente le permite hacer. La mayoría de las veces, los desarrolladores tienen que pasar por problemas de GitHub para comprender algunos conceptos básicos.
Este es un tema candente entre los marcos multiplataforma móviles y, a veces, se puede denominar una parte eficiente del tiempo del desarrollo móvil.
React Native : durante mucho tiempo, la recarga en caliente fue una de las debilidades que alejó a los desarrolladores de esta solución multiplataforma. Sin embargo, en React Native 0.61, anunciaron Fast Refresh , que NO es exactamente una recarga en caliente , pero también hace felices a los desarrolladores de RN.
Lo increíble de la actualización rápida es que es totalmente compatible con React moderno (componentes de funciones y ganchos) y maneja errores con gracia.
Flutter : Es un placer trabajar con la función de recarga en caliente de Flutter. Es tan bueno que flutter proporciona 3 formas diferentes de recargar su aplicación mientras trabaja: recarga en caliente, reinicio en caliente y reinicio completo.
Hay algunas advertencias que están muy bien explicadas y elaboradas en sus documentos, pero estas no impiden que esta característica sea uno de los mejores puntos de venta de Flutter para los desarrolladores.
Xamarin : al igual que con los otros 4 marcos, la recarga en caliente de Xamarin funciona de forma inmediata. Sin configuración adicional, puede guardar sus archivos y activar una actualización. La recarga en caliente de Xamarin funciona en varias plataformas a la vez y usa un principio llamado recarga resistente .
También hay algunos problemas con la recarga activa de Xamarin: no puede recargar el código C#, incluidos los controladores de eventos, los controles personalizados, el código subyacente de la página y las clases adicionales. Además, no puede cambiar archivos durante una sesión de recarga en caliente. Para ver este cambio, deberá reconstruir y volver a implementar su aplicación para volver a habilitar la recarga en caliente
Ionic : la recarga en vivo en Ionic se puede ver de dos maneras, porque las aplicaciones de Ionic se pueden desarrollar utilizando dos enfoques diferentes. Uno puede usar el navegador para codificar la aplicación y ver los resultados, o puede conectar su teléfono a la computadora para poder evaluarlo desde allí. Sin embargo, Ionic tiene una función completa de recarga en caliente que lo ayudará a desarrollar su aplicación de manera eficiente, independientemente del enfoque que elija.
NativeScript : desde Native script 5.3, es oficialmente compatible con una increíble función HMR - Hot Module Replacement que admite la depuración de VSCode, ediciones de estilo, ediciones de JavaScript e incluso ediciones de archivos.
La función LiveSync , que se ejecuta cuando iniciamos una run or debug on device
, también permite, como en el caso de Ionic, realizar cambios en su aplicación y ver los aplicados en tiempo real en todos los dispositivos y emuladores conectados.
Los desarrolladores a veces dicen que "la depuración es el doble de difícil que escribir el código en primer lugar". Dado que esto puede considerarse una de las partes más difíciles de nuestro trabajo, ¿por qué cualquier herramienta debería hacerlo más difícil?
La depuración multiplataforma móvil siempre ha sido incómoda, porque las herramientas no solo son híbridas, sino que también pueden no ser siempre compatibles de forma nativa.
Aquí, durante la comparación, combinaremos las herramientas de depuración y las funciones de informe de errores del marco.
React Native : al igual que con la recarga en caliente, la depuración con React Native siempre ha sido "incompleta", ya que el equipo central no admitía oficialmente ninguna herramienta.
Sin embargo, en React Native 0.62, anunciaron Flipper , que es el depurador de RN predeterminado desde el 26 de marzo. Flipper tiene excelentes funciones necesarias en un depurador, en particular:
Flutter : Flutter DevTools es una característica muy potente y completa. Se adapta a casi todos los casos de uso, desde salidas de consola simples, pasando por análisis de widgets visuales hasta inspección de red y rendimiento.
Flutter probablemente tiene la mejor función de depuración entre los 5 marcos.
Xamarin : Xamarin depura las aplicaciones de Android e iOS de manera diferente. Las aplicaciones de Android se depuran como cualquier otra aplicación .NET: después de ejecutar el dispositivo con la configuración de depuración, simplemente podemos agregar puntos de interrupción y seguir la ejecución de nuestra aplicación.
Xamarin.iOS usa el depurador Mono Soft , el código generado y el tiempo de ejecución Mono cooperan con el IDE para proporcionar una experiencia de depuración.
Ionic : en sus documentos, Ionic proporciona una amplia gama de funciones de depuración, ya que los marcos crean aplicaciones híbridas (HTML, CSS y JavaScript en una vista web) que se pueden depurar fácilmente con los depuradores web.
En caso de que desee ver mejores registros o una depuración más profunda, Cordova proporciona una extensión de VSCode que se adaptará a casi todas sus necesidades.
NativeScript : con el comando tns debug <platform>
, podemos iniciar fácilmente una sesión de depuración con NativeScript e iniciar Livesync.
Sin embargo, el resultado de la depuración se imprime en la consola y todos los cambios que realice se sincronizan con la aplicación. Sin embargo, cabe señalar que la extensión VSCode permite una experiencia de depuración mucho mejor.
Además, esta publicación de blog sobre cómo depurar los complementos de NativeScript ayuda a los desarrolladores a profundizar en la creación y depuración de aplicaciones con el esquema de NativeScript, que explica cómo los desarrolladores pueden abordar la depuración del código fuente nativo de los complementos que usan.
Los anteriores son los principales factores que atraen y mantienen a los desarrolladores en una herramienta que utilizan. Ahora veamos las cosas opcionales que hacen que los desarrolladores disfruten el tiempo que pasan trabajando con herramientas multiplataforma.
De los 5 marcos anteriores, Flutter puede sonar como el mejor debido a la potencia de los complementos y las integraciones que envían para los diferentes editores que admiten.
Después de instalar las extensiones de Flutter en VSCode , rápidamente comienza a sentirse como si se hubiera convertido en un IDE con soporte completo de depuración, fragmentos de andamiaje, hermoso resaltado de sintaxis y finalización de código.
Aunque no es tan avanzado como las herramientas de Flutter, React Native también tiene React Native Tools de Microsoft para ayudarlo a ejecutar y depurar rápida y fácilmente sus aplicaciones React Native.
Xamarin bien porque VS2019 le brinda todo lo que necesita para el desarrollo de Xamarin cuando decide instalar el marco. Esto mantiene al desarrollador en la herramienta porque todo lo que pueden obtener es todo lo que necesitan del IDE.
Con Ionic y NativeScript, está bien con la mayoría de los editores de desarrollo web porque usan herramientas de interfaz de usuario populares como HTML, JSX, CSS, SASS, Angular, React y Vue, que ya tienen un buen soporte en los editores existentes.
Las aplicaciones Advanced React Native dependen en gran medida de módulos de terceros, que pueden convertirse rápidamente en un rompecabezas cuando se actualizan con partes faltantes debido a la compatibilidad con otros módulos o con la versión actual del marco.
Sin embargo, la comunidad React Native es asombrosamente grande, por lo que hay muchos paquetes de código abierto disponibles en npm que podrían ser muy útiles para crear aplicaciones.
Este problema es menor en Flutter y Xamarin porque están listos con la mayor parte de lo que necesitamos para crear aplicaciones multiplataforma y su proceso de actualización está bien administrado por los respectivos archivos YAML y XML.
Flutter tiene su propio sitio web de administración de paquetes donde puede buscar y ver ejemplos de uso de los paquetes de Flutter.
Ionic en sí viene con la mayoría de los componentes de la interfaz de usuario necesarios para crear material o aplicaciones de interfaz de usuario de iOS, y respetan las pautas de diseño. Sin embargo, depende en gran medida de los complementos nativos de Cordova para acceder a las funcionalidades nativas, que a su vez pueden no estar actualizadas o carecer de documentación.
NativeScript, como Ionic, se incluye con una gran cantidad de componentes de interfaz de usuario atractivos. Sin embargo, los complementos nativos están disponibles y desarrollados por el equipo de NativeScript y su comunidad y se muestran en un Marketplace dedicado .
Los cinco marcos tienen una gran comunidad y ya son conocidos como las principales herramientas multiplataforma, debido a su amplio uso entre las empresas. Cada uno de ellos tiene flujos de trabajo únicos que pueden adaptarse a cada caso de uso.
Sin embargo, es importante comprender las fortalezas y limitaciones de cada uno y elegir de acuerdo con la tarea y el equipo con el que está tratando.
Fuente: https://blog.logrocket.com/comparing-developer-experience-for-cross-platform-frameworks/
1649264520
クロスプラットフォームのモバイルアプリ開発では、1つのテクノロジースタックでiOSやAndroidなどの複数のプラットフォーム向けのモバイルアプリケーションを構築できます。
つまり、プラットフォームごとに専用の母国語を使用して記述されたアプリの複数のバージョンを作成する代わりに、コードを1回記述して、一度に複数のプラットフォームにデプロイできます。
開発者エクスペリエンス(DXと略記)は、開発者がクライアントライブラリ、SDK、フレームワーク、オープンソースコード、ツール、API、テクノロジー、またはその他のサービスを使用するときのエクスペリエンスを表します。
DXは、ユーザーエクスペリエンス(UX)デザインからのいくつかのアイデアと哲学を共有しています。
単一のターミナルコマンドでWebアプリをデプロイする機会は、同じ結果を達成するための長い指示のリストに従うのではなく、より優れた開発者エクスペリエンスとして認識できるものを示しています。
DXは、開発者がツールを使用してそれに固執するように駆り立てる潜在的な要因の1つです。
この投稿では、開発者にとって本当に重要な4つの要素に基づいて、いくつかの人気のあるクロスプラットフォームモバイルフレームワークのDXを比較しています。
私たちの比較では、5つのクロスプラットフォームフレームワークに焦点を当てます。
フレームワークのセットアップが第一印象です。簡単に始めることが、フレームワークのワークフローに関してDXに最初に影響を与えるものです。
ここでは、Android StudioやXCodeのセットアップを無視して、さまざまなモバイルフレームワークのセットアッププロセスを比較します。これは、基本的にすべてのフレームワークにとって必須の手順だからです。
React Native:Expoを使用すると、ReactNativeを非常に簡単に開始できます。
NodeJSとExpoをインストールした後は、入力するコマンドが1つだけで、準備が整います(Android StudioまたはXcodeをインストールせずに、Expoアプリがインストールされたデバイスがあることを前提としています)。開始テンプレートには、開発者をガイドするのに役立つ美しくシンプルなインターフェイスが付属しています。
RNコマンドラインツールを使用して、ExpoなしでReactNativeアプリを起動することもできます。この方法を使用してRNアプリを実行するのは、それほど手間がかかりません。CLIツールは、開発者が最初の画面アプリをすぐに入手するのに役立ちます。
RNの使用を開始するには、RNを既存のネイティブアプリに統合する必要がある場合、またはツリー外のプラットフォーム用に構築する必要がある場合にのみ注意が必要です。ただし、これは高度な方法と見なされるため、この比較では考慮しないでください。
React Nativeは宿題をうまくやっているのでreact-native doctor
、コンピューターのセットアップを確認するのに役立つパッケージもリリースしました。
Flutter:Flutter SDKをインストールするのは、コンピューターにパッケージをインストールするのと同じくらい簡単です。彼らのガイドは、従うのが簡単な4つの簡単なステップを示しています。これがあなたの側で少しバグがあるとしても、Flutterはあなたをカバーしてくれます。
彼らはDXを大事にすることでよく知られています。彼らはCLIに呼び出されるツールを統合しflutter doctor
て、フレームワークのツールチェーンで何がうまく機能していて何がうまく機能しないかについての情報を取得できるようにしました。
より良いDXを提供するには、Flutterツールもコードエディターで構成する必要があります。これは、セットアップのいくつかの追加手順を説明します。これらの手順はオプションですが、インターネット上で最高のFlutterレビューを達成するのに役立ちました。
Flutterのすべてが「すぐに使える」と感じます。Flutter SDKに同梱されているパッケージのみを使用して、より複雑なアプリを簡単に構築できます。
Xamarin:Visual Studio IDEに慣れているC#開発者の場合、Xamarinのインストールは確かに公園を散歩しているように見えます。ただし、Visual Studioがない場合は、VS2019のインストールとXamarinツールが面倒になる可能性があります。
Xamarinをインストールすると、Visual Studio GettingStartedGUIを使用してアプリを起動できます。ここでは、モバイルアプリを選択し、提供されているテンプレート(マスター詳細、タブ付き、シェル、空白)から開始テンプレートを選択します。次に、プラットフォームを選択し、[続行]をクリックして、初期化されるのを待ちます。
Ionic:v1以降、Ionicは常に非常に簡単に使い始めることができます。現在、v5を使用しており、さらに簡単になっています。
これは3つのステップでionic start myApp <template-name>
行われます。IonicwithNodeをインストールし、(空白、タブ、サイドメニューの3つのテンプレートが提供されている)のプロンプトを実行して実行し、最後に。を使用してアプリを実行しionic serve
ます。
ここでは、デフォルトのアプリがモバイルWebサイトのようにブラウザで提供されますが、これはビルド後のアプリの外観とほぼ同じです。
また、Ionicにはv5があります。これは、1つのコマンドライン命令だけで上記と同じ結果を得るのに役立つ、美しく直感的な起動ウィザードです。
NativeScript:開始するには、クイックセットアップとフルセットアップの2つの方法があります。クイックセットアッププロセスは、React Native with Expoに似ています。物理デバイスにアプリをダウンロードすると、React Nativeがリンクを介して開発端末に接続し、アプリの作業を開始できます(Android StudioまたはXCodeをインストールせずに) 。
フレームワークをインストールするためにOSの端末とうまく機能するリンクを提供するため、フルセットアップも簡単です。さらに、Flutterと同様に、次のコマンドでアクセスできるドクターツールがありますtns doctor
。これは、コンピューターのセットアップを確認します。
注:
ほとんどのクイックセットアップには、ワークフローにいくつかの制限があることに注意してください。たとえば、一部のネイティブプラグインへのアクセスが制限され、単体テストが不可能な場合があり(NativeScriptの場合)、一部のリソース(スプラッシュ画面、アイコン)にアクセスできません。
開発者なら誰でも、ツールのマニュアルを使いやすくすることで、ツールに夢中になることがあることを認めることができます。
React Native:最近、React Nativeのドキュメントにいくつかの大きな改善が加えられましたが、React Native開発者は、ブログ投稿、オンラインチュートリアル、コースなどのリソースから高度なトピックに触れる傾向があります。
これは、中級から上級レベルまでのReact Nativeトピックが、コアAPIによって提案されたものよりもはるかに多くの(状態管理、ナビゲーション、アニメーションなど)を要求するという事実に関連しているようです。
Flutter:Flutterのドキュメントは、5つのフレームワークの中で最も愛されている必要があります。彼らは、誰もがそれらを通り抜けるのを助けるために組織化された情報でそれを氾濫させました。単純なコマンドから、短い有益なビデオやウィジェットクラスを含むクックブックに至るまで、Flutterのドキュメントは非常によく提示されています。ウィジェットのクラス参照APIは、ウィジェットの各ソースコードから簡単にアクセスできることを述べましたか?
Xamarin:Xamarin開発者は、ドキュメントが「フル」であると言っています。これは本当です。Xamarinには、5つのドキュメントのうち、フレームワークのトピックに関する洞察が必要なときにいつでも戻ってくるドキュメントの1つがあります。
ドキュメントの資料だけで、初心者から上級者までかなりうまく行くことができます。そのナビゲーションは本当に直感的で、トピックとユースケースに関する未解決の問題への短いチュートリアルとリンクが含まれています。
Ionic:Ionicが彼らのドキュメントに驚くべき仕事をしていることは明らかです。メジャーアップデートのたびに、Webサイト全体が変更され、ユーザーエクスペリエンスが向上します。
Ionicを使用する開発者のほとんどは、必要なコンポーネントを簡単に検索、検索、統合できると感じています。
NativeScript:NativeScriptの1つは、宣伝するものよりもはるかに優れていることです。NativeScriptのドキュメントは非常に基本的です。フレームワークの能力を活用することがいかに簡単であるかを開発者に示すために、より多くのガイドが必要です。
さらに、初心者から熟練者に移行しようとすると、NativeScriptのドキュメントには、フレームワークで実際に実行できることの明確な例がいくつか欠けていると感じます。ほとんどの場合、開発者はいくつかの基本的な概念を理解するためにGitHubの問題を経験する必要があります。
これは、モバイルクロスプラットフォームフレームワークの中でホットなトピックであり、モバイル開発の時間効率の良い部分と呼ばれることもあります。
React Native:長い間、ホットリロードは開発者をこのクロスプラットフォームソリューションから遠ざける弱点の1つでした。ただし、React Native 0.61で、彼らはFast Refreshを発表しました。これは、正確にはホットリロードではありませんが、RN開発者も満足させます。
高速リフレッシュの素晴らしい点は、最新のReact(関数コンポーネントとフック)を完全にサポートし、エラーを適切に処理することです。
Flutter:Flutterのホットリロード機能は操作するのが楽しいです。非常に優れているため、フラッターは、作業中にアプリをリロードする3つの異なる方法、ホットリロード、ホットリスタート、およびフルリスタートを提供します。
ドキュメントで非常によく説明され、解決されているいくつかの警告がありますが、これらはこの機能が開発者にとってFlutterのベストセールスポイントの1つであることを妨げるものではありません。
Xamarin:他の4つのフレームワークと同様に、Xamarinのホットリロードはそのままで機能します。さらに設定しなくても、ファイルを保存して更新をトリガーできます。Xamarinのホットリロードは、一度に複数のプラットフォームで機能し、復元力のあるリロードと呼ばれる原則を使用します。
Xamarinのホットリロードにはいくつかの問題もあります。イベントハンドラー、カスタムコントロール、ページコードビハインド、追加のクラスなど、C#コードをリロードできません。また、ホットリロードセッション中にファイルを変更することはできません。この変更を表示するには、アプリを再構築して再デプロイし、ホットリロードを再度有効にする必要があります
Ionic:Ionicアプリは2つの異なるアプローチを使用して開発できるため、Ionicでのライブリロードは2つの方法で表示できます。ブラウザを使用してアプリをコーディングして結果を表示するか、電話をコンピュータに接続してそこから評価できるようにすることができます。それでも、Ionicには完全なホットリロード機能があり、選択したアプローチに関係なく、アプリを効率的に開発するのに役立ちます。
NativeScript:ネイティブスクリプト5.3以降、VSCodeからのデバッグ、スタイリング編集、JavaScript編集、さらにはファイル編集をサポートする素晴らしいHMR –ホットモジュール置換機能を公式にサポートしています。
開始時に実行されるLiveSync機能を使用するrun or debug on device
と、Ionicの場合と同様に、アプリに変更を加えて、接続されているすべてのデバイスとエミュレーターにリアルタイムで適用されたものを確認できます。
開発者は、「デバッグは、そもそもコードを書くよりも2倍難しい」と言うことがあります。これは私たちの仕事の中で最も難しい部分の1つと見なすことができるので、なぜツールがそれを難しくする必要があるのでしょうか。
ツールはハイブリッドであるだけでなく、常にネイティブに互換性があるとは限らないため、モバイルクロスプラットフォームのデバッグは常に不安でした。
ここでは、比較中に、フレームワークのデバッグツールとエラーレポート機能を組み合わせます。
React Native:ホットリロードと同様に、コアチームによって公式にサポートされているツールがないため、ReactNativeを使用したデバッグは常に「大雑把」でした。
ただし、React Native 0.62では、3月26日以降のデフォルトのRNデバッガーであるFlipperを発表しました。Flipperには、デバッガーに必要な優れた機能があります。
Flutter:Flutter DevToolsは、非常に強力で完全な機能です。シンプルなコンソール出力から、ビジュアルウィジェット分析、ネットワークおよびパフォーマンス検査に至るまで、ほぼすべてのユースケースに適合します。
Flutterは、おそらく5つのフレームワークの中で最高のデバッグ機能を備えています。
Xamarin:XamarinはAndroidアプリとiOSアプリを異なる方法でデバッグします。Androidアプリは、他の.NETアプリケーションと同じようにデバッグされます。デバッグ構成でデバイスを実行した後、ブレークポイントを追加してアプリの実行を追跡できます。
Xamarin.iOSは、Mono Softデバッガー、生成されたコード、およびMonoランタイムをIDEと連携して使用し、デバッグエクスペリエンスを提供します。
Ionic :彼らのドキュメントでは 、フレームワークがWebデバッガーを使用して簡単にデバッグ可能なハイブリッドアプリ(WebビューのHTML、CSS、JavaScript)を作成するため、Ionicは幅広いデバッグ機能を提供します。
より良いログまたはより深いデバッグを表示したい場合、 Cordovaはほとんどすべてのニーズに適合するVSCode拡張機能を提供します。
NativeScript:コマンドtns debug <platform>
を使用すると、NativeScriptを使用してデバッグセッションを簡単に開始し、Livesyncを開始できます。
ただし、デバッグの出力はコンソールに出力され、行ったすべての変更はアプリと同期されます。ただし、 VSCode拡張機能を使用すると、はるかに優れたデバッグエクスペリエンスが可能になることに注意してください。
さらに、NativeScriptプラグインのデバッグに関するこのブログ投稿は、開発者が使用するプラグインのネイティブソースコードのデバッグにどのように取り組むことができるかを説明する、NativeScriptアウトラインを使用したアプリの構築とデバッグに深く取り組むのに役立ちます。
上記は、開発者が使用するツールを引き付け、維持する主な要因です。次に、開発者がクロスプラットフォームツールでの作業に費やす時間を楽しむことができるオプションのものを見てみましょう。
上記の5つのフレームワークのうち、Flutterは、サポートするさまざまなエディター用に出荷されるプラグインと統合のパワーにより、最高のように聞こえるかもしれません。
Flutter拡張機能をVSCodeにインストールすると、完全なデバッグサポート、スキャフォールディングスニペット、美しい構文の強調表示、およびコード補完を備えたIDEになっているようにすぐに感じ始めます。
Flutterのツールほど高度ではありませんが、React Nativeには、ReactNativeアプリをすばやく簡単に実行およびデバッグするのに役立つMicrosoftのReactNativeToolsもあります。
Xamarinは、フレームワークのインストールを決定したときにVS2019がXamarin開発に必要なすべてを提供するため優れています。これにより、開発者はIDEから必要なものをすべて取得できるため、開発者はツールに固執します。
IonicとNativeScriptを使用すると、HTML、JSX、CSS、SASS、Angular、React、Vueなどの人気のあるフロントエンドツールを使用するため、ほとんどのWeb開発エディターで問題ありません。これらのツールは既存のエディターですでに十分にサポートされています。
Advanced React Nativeアプリは、サードパーティのモジュールに大きく依存しています。サードパーティのモジュールは、他のモジュールや現在のバージョンのフレームワークとの互換性のために、不足している部分で更新するとすぐにパズルになる可能性があります。
ただし、React Nativeコミュニティは驚くほど大きいため、アプリの構築に非常に役立つ可能性のある多くのオープンソースパッケージがnpmで利用できます。
この問題は、FlutterとXamarinのマイナーな問題です。これは、クロスプラットフォームアプリを構築するために必要なほとんどの準備が整っており、更新プロセスがそれぞれのYAMLファイルとXMLファイルによって適切に管理されているためです。
Flutterには独自のパッケージマネージャーWebサイト があり、Flutterパッケージの使用例を検索および表示できます。
Ionic自体には、マテリアルまたはiOS UIアプリの構築に必要なほとんどのUIコンポーネントが付属しており、設計ガイドラインを尊重しています。ただし、ネイティブ機能にアクセスするには、Cordovaのネイティブプラグインに強く依存しています。これらのプラグインは、最新ではないか、ドキュメントが不足している可能性があります。
NativeScriptは、Ionicと同様に、見栄えの良いUIコンポーネントが多数バンドルされています。ただし、ネイティブプラグインは、NativeScriptのチームとそのコミュニティによって利用および開発され、専用のマーケットプレイスで紹介されています。
5つのフレームワークはすべて大きなコミュニティを持っており、企業間で広く使用されているため、すでに主要なクロスプラットフォームツールとして知られています。それぞれに独自のワークフローがあり、それぞれのユースケースに合わせて調整できます。
それでも、それぞれの長所と制限を理解し、どのタスクとチームを扱っているかに応じて選択することが重要です。
ソース:https ://blog.logrocket.com/comparing-developer-experience-for-cross-platform-frameworks/
1649028120
Micro frameworks and routers.
Author: ziadoz
Source Code: https://github.com/ziadoz/awesome-php
License: WTFPL License