1653897081
Neste tutorial, você aprenderá do que se trata o PyScript e como usá-lo em arquivos HTML para executar o código Python no navegador. Você também aprende sobre as várias operações/funcionalidades que você pode fazer com o PyScript.
O Python cresceu imensamente em popularidade nos últimos anos. Possui uma ampla gama de aplicações, desde seu uso mais popular em Inteligência Artificial, até Ciência de Dados, Robótica e Scripting.
No campo de desenvolvimento web, o Python é usado principalmente no backend com frameworks como Django e Flask.
Até agora, o Python não tinha muito suporte no front-end, como outras linguagens, como JavaScript. Mas, felizmente, os desenvolvedores do Python construíram algumas bibliotecas (como Brython ) para oferecer suporte à sua linguagem favorita na web.
E este ano, durante a conferência PyCon 2022 , a Anaconda anunciou um framework chamado PyScript que permite usar Python na web usando HTML padrão.
Você precisará das seguintes ferramentas e conhecimento para codificar junto com este artigo:
Fonte: site oficial do PyScript
PyScript é uma estrutura de front-end Python que permite aos usuários construir programas Python usando uma interface HTML no navegador.
Ele foi desenvolvido usando o poder de Emscripten , Pyodide , WASM e outras tecnologias modernas da web para fornecer as seguintes habilidades de acordo com seus objetivos:
Fonte: Blog Anaconda
Nas últimas duas décadas, Python e linguagens de interface do usuário avançadas, como HTML, CSS e JavaScript modernos, não funcionaram em colaboração. O Python carecia de um mecanismo simples para criar interfaces de usuário atraentes para simplesmente empacotar e implantar aplicativos, enquanto HTML, CSS e JavaScript atuais podem ter uma curva de aprendizado íngreme.
Permitir que o Python utilize convenções de HTML, CSS e JavaScript resolve não apenas esses dois problemas, mas também aqueles relacionados ao desenvolvimento, empacotamento, distribuição e implantação de aplicativos da Web.
No entanto, o PyScript não deve assumir o papel de JavaScript no navegador – em vez disso, destina-se a fornecer aos desenvolvedores Python, principalmente cientistas de dados, mais flexibilidade e poder.
O PyScript oferece uma linguagem de programação com convenções de estilo consistentes, mais expressividade e facilidade de aprendizado, fornecendo o seguinte:
O PyScript é bastante fácil e direto de aprender. Para começar, você pode seguir as instruções no site ou baixar o arquivo .zip .
Neste artigo, usaremos e aprenderemos a usar o PyScript por meio do site . Você pode fazer isso vinculando os componentes em seu arquivo HTML. Vamos imprimir nosso primeiro “Hello World” com PyScript.
Para começar, você precisará criar um arquivo HTML para exibir texto em seu navegador usando o editor de texto/IDE de sua escolha.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Title: PyScript</title>
</head>
<body>
</body>
</html>
Depois de criar o arquivo HTML, precisaremos vincular o PyScript em seu arquivo HTML para ter acesso à interface PyScript. Isso será colocado na <head>
etiqueta.
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
Agora que você vinculou o PyScript ao arquivo HTML, você pode imprimir seu “Hello World”.
Você pode fazer isso com a <py-script>
etiqueta. A <py-script>
tag permite executar programas Python de várias linhas e imprimi-los na página do navegador. Coloque a etiqueta entre as <body>
etiquetas.
<body> <py-script> print("Hello, World!") </py-script> </body>
O código completo do arquivo HTML está abaixo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Title: PyScript</title>
</head>
<body>
<py-script> print("Hello, World!") </py-script>
</body>
</html>
No seu navegador, você deve ver isso:
Dica: Se você estiver usando o editor VSCode, poderá usar o complemento Live Server no VSCode para recarregar a página à medida que atualiza o arquivo HTML.
Há mais operações que você pode realizar com a estrutura PyScript. Vejamos alguns deles agora.
Ao usar o PyScript, você pode querer passar variáveis do seu código Python para o HTML. Você pode fazer isso com o write
método do pyscript
módulo dentro da <pyscript>
tag. Usando o id
atributo , você passa strings exibidas como texto normal.
O método write aceita duas variáveis: o id
valor e a variável que será fornecida.
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<b><p>Today is <u><label id='today'></label></u></p></b>
<py-script>
import datetime as dt
pyscript.write('today', dt.date.today().strftime('%A %B %d, %Y'))
</py-script>
</body>
</html>
E a saída se torna:
O PyScript fornece uma interface para executar código Python em navegadores.
Para poder fazer isso, o PyScript usa a <py-repl>
tag. A <py-repl>
tag adiciona um componente REPL à página, que atua como um editor de código e permite escrever código executável embutido.
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<py-repl id="my-repl" auto-generate=true> </py-repl>
</html>
Experimentando no navegador (de preferência Chrome), você deve obter isto:
Uma das funções que o PyScript oferece é a flexibilidade. No PyScript você pode importar arquivos locais, módulos embutidos ou bibliotecas de terceiros. Este processo usa a <py-env>
tag. Esta tag é para declarar as dependências necessárias.
Para arquivos Python locais em seu sistema, você pode colocar o código em um .py
arquivo e os caminhos para os módulos locais são fornecidos na chave paths: na <py-env>
tag.
Vamos criar um arquivo Python example.py
para conter algumas funções:
from random import randint
def add_two_numbers(x, y):
return x + y
def generate_random_number():
x = randint(0, 10)
return x
Em seguida, o arquivo Python será importado para o HTML com a <py-env>
tag. Você deve colocar essa tag na <head>
tag, acima da <body>
tag.
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<py-env>
- paths:
- /example.py
</py-env>
</head>
<body>
<h1>Let's print random numbers</h1>
<b>Doe's lucky number is <label id="lucky"></label></b>
<py-script>
from example import generate_random_number
pyscript.write('lucky', generate_random_number())
</py-script>
</body>
</html>
Isso retornará:
Para bibliotecas de terceiros que não fazem parte da biblioteca padrão, o PyScript oferece suporte a elas.
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<py-env>
- numpy
- requests
</py-env>
</head>
<body>
<py-script>
import numpy as np
import requests
</py-script>
</body>
</html>
Você pode definir e configurar metadados gerais sobre seu aplicativo PyScript no formato YAML usando a <py config>
tag. Você pode usar esta tag neste formato:
<py-config>
- autoclose_loader: false
- runtimes:
-
src: "https://cdn.jsdelivr.net/pyodide/v0.20.0/full/pyodide.js"
name: pyodide-0.20
lang: python
</py-config>
Esses são os valores opcionais que a <py-config>
tag fornece. Eles incluem:
Neste artigo, você aprendeu sobre o que é o PyScript e como usá-lo em arquivos HTML para executar o código Python no navegador. Você também aprendeu sobre as várias operações/funcionalidades que você pode fazer com o PyScript.
Com o PyScript, é mais fácil executar e executar operações Python na web, pois isso não era fácil antes. Esta é uma ótima ferramenta para quem está ansioso para usar Python na web.
O PyScript ainda está em seus estágios iniciais e sob forte desenvolvimento. Ele ainda está em seu estágio alfa e enfrenta problemas conhecidos, como o tempo de carregamento, que pode afetar a usabilidade (algumas outras operações não podem ser exibidas no momento da redação deste artigo devido a problemas de desempenho). Portanto, você não deve usá-lo em produção ainda, pois provavelmente haverá muitas alterações importantes.
Fonte do artigo original em https://www.freecodecamp.org
1651383480
This serverless plugin is a wrapper for amplify-appsync-simulator made for testing AppSync APIs built with serverless-appsync-plugin.
Install
npm install serverless-appsync-simulator
# or
yarn add serverless-appsync-simulator
Usage
This plugin relies on your serverless yml file and on the serverless-offline
plugin.
plugins:
- serverless-dynamodb-local # only if you need dynamodb resolvers and you don't have an external dynamodb
- serverless-appsync-simulator
- serverless-offline
Note: Order is important serverless-appsync-simulator
must go before serverless-offline
To start the simulator, run the following command:
sls offline start
You should see in the logs something like:
...
Serverless: AppSync endpoint: http://localhost:20002/graphql
Serverless: GraphiQl: http://localhost:20002
...
Configuration
Put options under custom.appsync-simulator
in your serverless.yml
file
| option | default | description | | ------------------------ | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | | apiKey | 0123456789
| When using API_KEY
as authentication type, the key to authenticate to the endpoint. | | port | 20002 | AppSync operations port; if using multiple APIs, the value of this option will be used as a starting point, and each other API will have a port of lastPort + 10 (e.g. 20002, 20012, 20022, etc.) | | wsPort | 20003 | AppSync subscriptions port; if using multiple APIs, the value of this option will be used as a starting point, and each other API will have a port of lastPort + 10 (e.g. 20003, 20013, 20023, etc.) | | location | . (base directory) | Location of the lambda functions handlers. | | refMap | {} | A mapping of resource resolutions for the Ref
function | | getAttMap | {} | A mapping of resource resolutions for the GetAtt
function | | importValueMap | {} | A mapping of resource resolutions for the ImportValue
function | | functions | {} | A mapping of external functions for providing invoke url for external fucntions | | dynamoDb.endpoint | http://localhost:8000 | Dynamodb endpoint. Specify it if you're not using serverless-dynamodb-local. Otherwise, port is taken from dynamodb-local conf | | dynamoDb.region | localhost | Dynamodb region. Specify it if you're connecting to a remote Dynamodb intance. | | dynamoDb.accessKeyId | DEFAULT_ACCESS_KEY | AWS Access Key ID to access DynamoDB | | dynamoDb.secretAccessKey | DEFAULT_SECRET | AWS Secret Key to access DynamoDB | | dynamoDb.sessionToken | DEFAULT_ACCESS_TOKEEN | AWS Session Token to access DynamoDB, only if you have temporary security credentials configured on AWS | | dynamoDb.* | | You can add every configuration accepted by DynamoDB SDK | | rds.dbName | | Name of the database | | rds.dbHost | | Database host | | rds.dbDialect | | Database dialect. Possible values (mysql | postgres) | | rds.dbUsername | | Database username | | rds.dbPassword | | Database password | | rds.dbPort | | Database port | | watch | - *.graphql
- *.vtl | Array of glob patterns to watch for hot-reloading. |
Example:
custom:
appsync-simulator:
location: '.webpack/service' # use webpack build directory
dynamoDb:
endpoint: 'http://my-custom-dynamo:8000'
Hot-reloading
By default, the simulator will hot-relad when changes to *.graphql
or *.vtl
files are detected. Changes to *.yml
files are not supported (yet? - this is a Serverless Framework limitation). You will need to restart the simulator each time you change yml files.
Hot-reloading relies on watchman. Make sure it is installed on your system.
You can change the files being watched with the watch
option, which is then passed to watchman as the match expression.
e.g.
custom:
appsync-simulator:
watch:
- ["match", "handlers/**/*.vtl", "wholename"] # => array is interpreted as the literal match expression
- "*.graphql" # => string like this is equivalent to `["match", "*.graphql"]`
Or you can opt-out by leaving an empty array or set the option to false
Note: Functions should not require hot-reloading, unless you are using a transpiler or a bundler (such as webpack, babel or typescript), un which case you should delegate hot-reloading to that instead.
Resource CloudFormation functions resolution
This plugin supports some resources resolution from the Ref
, Fn::GetAtt
and Fn::ImportValue
functions in your yaml file. It also supports some other Cfn functions such as Fn::Join
, Fb::Sub
, etc.
Note: Under the hood, this features relies on the cfn-resolver-lib package. For more info on supported cfn functions, refer to the documentation
You can reference resources in your functions' environment variables (that will be accessible from your lambda functions) or datasource definitions. The plugin will automatically resolve them for you.
provider:
environment:
BUCKET_NAME:
Ref: MyBucket # resolves to `my-bucket-name`
resources:
Resources:
MyDbTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: myTable
...
MyBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: my-bucket-name
...
# in your appsync config
dataSources:
- type: AMAZON_DYNAMODB
name: dynamosource
config:
tableName:
Ref: MyDbTable # resolves to `myTable`
Sometimes, some references cannot be resolved, as they come from an Output from Cloudformation; or you might want to use mocked values in your local environment.
In those cases, you can define (or override) those values using the refMap
, getAttMap
and importValueMap
options.
refMap
takes a mapping of resource name to value pairsgetAttMap
takes a mapping of resource name to attribute/values pairsimportValueMap
takes a mapping of import name to values pairsExample:
custom:
appsync-simulator:
refMap:
# Override `MyDbTable` resolution from the previous example.
MyDbTable: 'mock-myTable'
getAttMap:
# define ElasticSearchInstance DomainName
ElasticSearchInstance:
DomainEndpoint: 'localhost:9200'
importValueMap:
other-service-api-url: 'https://other.api.url.com/graphql'
# in your appsync config
dataSources:
- type: AMAZON_ELASTICSEARCH
name: elasticsource
config:
# endpoint resolves as 'http://localhost:9200'
endpoint:
Fn::Join:
- ''
- - https://
- Fn::GetAtt:
- ElasticSearchInstance
- DomainEndpoint
In some special cases you will need to use key-value mock nottation. Good example can be case when you need to include serverless stage value (${self:provider.stage}
) in the import name.
This notation can be used with all mocks - refMap
, getAttMap
and importValueMap
provider:
environment:
FINISH_ACTIVITY_FUNCTION_ARN:
Fn::ImportValue: other-service-api-${self:provider.stage}-url
custom:
serverless-appsync-simulator:
importValueMap:
- key: other-service-api-${self:provider.stage}-url
value: 'https://other.api.url.com/graphql'
This plugin only tries to resolve the following parts of the yml tree:
provider.environment
functions[*].environment
custom.appSync
If you have the need of resolving others, feel free to open an issue and explain your use case.
For now, the supported resources to be automatically resovled by Ref:
are:
Feel free to open a PR or an issue to extend them as well.
External functions
When a function is not defined withing the current serverless file you can still call it by providing an invoke url which should point to a REST method. Make sure you specify "get" or "post" for the method. Default is "get", but you probably want "post".
custom:
appsync-simulator:
functions:
addUser:
url: http://localhost:3016/2015-03-31/functions/addUser/invocations
method: post
addPost:
url: https://jsonplaceholder.typicode.com/posts
method: post
Supported Resolver types
This plugin supports resolvers implemented by amplify-appsync-simulator
, as well as custom resolvers.
From Aws Amplify:
Implemented by this plugin
#set( $cols = [] )
#set( $vals = [] )
#foreach( $entry in $ctx.args.input.keySet() )
#set( $regex = "([a-z])([A-Z]+)")
#set( $replacement = "$1_$2")
#set( $toSnake = $entry.replaceAll($regex, $replacement).toLowerCase() )
#set( $discard = $cols.add("$toSnake") )
#if( $util.isBoolean($ctx.args.input[$entry]) )
#if( $ctx.args.input[$entry] )
#set( $discard = $vals.add("1") )
#else
#set( $discard = $vals.add("0") )
#end
#else
#set( $discard = $vals.add("'$ctx.args.input[$entry]'") )
#end
#end
#set( $valStr = $vals.toString().replace("[","(").replace("]",")") )
#set( $colStr = $cols.toString().replace("[","(").replace("]",")") )
#if ( $valStr.substring(0, 1) != '(' )
#set( $valStr = "($valStr)" )
#end
#if ( $colStr.substring(0, 1) != '(' )
#set( $colStr = "($colStr)" )
#end
{
"version": "2018-05-29",
"statements": ["INSERT INTO <name-of-table> $colStr VALUES $valStr", "SELECT * FROM <name-of-table> ORDER BY id DESC LIMIT 1"]
}
#set( $update = "" )
#set( $equals = "=" )
#foreach( $entry in $ctx.args.input.keySet() )
#set( $cur = $ctx.args.input[$entry] )
#set( $regex = "([a-z])([A-Z]+)")
#set( $replacement = "$1_$2")
#set( $toSnake = $entry.replaceAll($regex, $replacement).toLowerCase() )
#if( $util.isBoolean($cur) )
#if( $cur )
#set ( $cur = "1" )
#else
#set ( $cur = "0" )
#end
#end
#if ( $util.isNullOrEmpty($update) )
#set($update = "$toSnake$equals'$cur'" )
#else
#set($update = "$update,$toSnake$equals'$cur'" )
#end
#end
{
"version": "2018-05-29",
"statements": ["UPDATE <name-of-table> SET $update WHERE id=$ctx.args.input.id", "SELECT * FROM <name-of-table> WHERE id=$ctx.args.input.id"]
}
{
"version": "2018-05-29",
"statements": ["UPDATE <name-of-table> set deleted_at=NOW() WHERE id=$ctx.args.id", "SELECT * FROM <name-of-table> WHERE id=$ctx.args.id"]
}
#set ( $index = -1)
#set ( $result = $util.parseJson($ctx.result) )
#set ( $meta = $result.sqlStatementResults[1].columnMetadata)
#foreach ($column in $meta)
#set ($index = $index + 1)
#if ( $column["typeName"] == "timestamptz" )
#set ($time = $result["sqlStatementResults"][1]["records"][0][$index]["stringValue"] )
#set ( $nowEpochMillis = $util.time.parseFormattedToEpochMilliSeconds("$time.substring(0,19)+0000", "yyyy-MM-dd HH:mm:ssZ") )
#set ( $isoDateTime = $util.time.epochMilliSecondsToISO8601($nowEpochMillis) )
$util.qr( $result["sqlStatementResults"][1]["records"][0][$index].put("stringValue", "$isoDateTime") )
#end
#end
#set ( $res = $util.parseJson($util.rds.toJsonString($util.toJson($result)))[1][0] )
#set ( $response = {} )
#foreach($mapKey in $res.keySet())
#set ( $s = $mapKey.split("_") )
#set ( $camelCase="" )
#set ( $isFirst=true )
#foreach($entry in $s)
#if ( $isFirst )
#set ( $first = $entry.substring(0,1) )
#else
#set ( $first = $entry.substring(0,1).toUpperCase() )
#end
#set ( $isFirst=false )
#set ( $stringLength = $entry.length() )
#set ( $remaining = $entry.substring(1, $stringLength) )
#set ( $camelCase = "$camelCase$first$remaining" )
#end
$util.qr( $response.put("$camelCase", $res[$mapKey]) )
#end
$utils.toJson($response)
Variable map support is limited and does not differentiate numbers and strings data types, please inject them directly if needed.
Will be escaped properly: null
, true
, and false
values.
{
"version": "2018-05-29",
"statements": [
"UPDATE <name-of-table> set deleted_at=NOW() WHERE id=:ID",
"SELECT * FROM <name-of-table> WHERE id=:ID and unix_timestamp > $ctx.args.newerThan"
],
variableMap: {
":ID": $ctx.args.id,
## ":TIMESTAMP": $ctx.args.newerThan -- This will be handled as a string!!!
}
}
Requires
Author: Serverless-appsync
Source Code: https://github.com/serverless-appsync/serverless-appsync-simulator
License: MIT License
1648972740
Generis
Versatile Go code generator.
Generis is a lightweight code preprocessor adding the following features to the Go language :
package main;
// -- IMPORTS
import (
"html"
"io"
"log"
"net/http"
"net/url"
"strconv"
);
// -- DEFINITIONS
#define DebugMode
#as true
// ~~
#define HttpPort
#as 8080
// ~~
#define WriteLine( {{text}} )
#as log.Println( {{text}} )
// ~~
#define local {{variable}} : {{type}};
#as var {{variable}} {{type}};
// ~~
#define DeclareStack( {{type}}, {{name}} )
#as
// -- TYPES
type {{name}}Stack struct
{
ElementArray []{{type}};
}
// -- INQUIRIES
func ( stack * {{name}}Stack ) IsEmpty(
) bool
{
return len( stack.ElementArray ) == 0;
}
// -- OPERATIONS
func ( stack * {{name}}Stack ) Push(
element {{type}}
)
{
stack.ElementArray = append( stack.ElementArray, element );
}
// ~~
func ( stack * {{name}}Stack ) Pop(
) {{type}}
{
local
element : {{type}};
element = stack.ElementArray[ len( stack.ElementArray ) - 1 ];
stack.ElementArray = stack.ElementArray[ : len( stack.ElementArray ) - 1 ];
return element;
}
#end
// ~~
#define DeclareStack( {{type}} )
#as DeclareStack( {{type}}, {{type:PascalCase}} )
// -- TYPES
DeclareStack( string )
DeclareStack( int32 )
// -- FUNCTIONS
func HandleRootPage(
response_writer http.ResponseWriter,
request * http.Request
)
{
local
boolean : bool;
local
natural : uint;
local
integer : int;
local
real : float64;
local
escaped_html_text,
escaped_url_text,
text : string;
local
integer_stack : Int32Stack;
boolean = true;
natural = 10;
integer = 20;
real = 30.0;
text = "text";
escaped_url_text = "&escaped text?";
escaped_html_text = "<escaped text/>";
integer_stack.Push( 10 );
integer_stack.Push( 20 );
integer_stack.Push( 30 );
#write response_writer
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><%= request.URL.Path %></title>
</head>
<body>
<% if ( boolean ) { %>
<%= "URL : " + request.URL.Path %>
<br/>
<%@ natural %>
<%# integer %>
<%& real %>
<br/>
<%~ text %>
<%^ escaped_url_text %>
<%= escaped_html_text %>
<%= "<%% ignored %%>" %>
<%% ignored %%>
<% } %>
<br/>
Stack :
<br/>
<% for !integer_stack.IsEmpty() { %>
<%# integer_stack.Pop() %>
<% } %>
</body>
</html>
#end
}
// ~~
func main()
{
http.HandleFunc( "/", HandleRootPage );
#if DebugMode
WriteLine( "Listening on http://localhost:HttpPort" );
#end
log.Fatal(
http.ListenAndServe( ":HttpPort", nil )
);
}
Constants and generic code can be defined with the following syntax :
#define old code
#as new code
#define old code
#as
new
code
#end
#define
old
code
#as new code
#define
old
code
#as
new
code
#end
The #define
directive can contain one or several parameters :
{{variable name}} : hierarchical code (with properly matching brackets and parentheses)
{{variable name#}} : statement code (hierarchical code without semicolon)
{{variable name$}} : plain code
{{variable name:boolean expression}} : conditional hierarchical code
{{variable name#:boolean expression}} : conditional statement code
{{variable name$:boolean expression}} : conditional plain code
They can have a boolean expression to require they match specific conditions :
HasText text
HasPrefix prefix
HasSuffix suffix
HasIdentifier text
false
true
!expression
expression && expression
expression || expression
( expression )
The #define
directive must not start or end with a parameter.
The #as
directive can use the value of the #define
parameters :
{{variable name}}
{{variable name:filter function}}
{{variable name:filter function:filter function:...}}
Their value can be changed through one or several filter functions :
LowerCase
UpperCase
MinorCase
MajorCase
SnakeCase
PascalCase
CamelCase
RemoveComments
RemoveBlanks
PackStrings
PackIdentifiers
ReplacePrefix old_prefix new_prefix
ReplaceSuffix old_suffix new_suffix
ReplaceText old_text new_text
ReplaceIdentifier old_identifier new_identifier
AddPrefix prefix
AddSuffix suffix
RemovePrefix prefix
RemoveSuffix suffix
RemoveText text
RemoveIdentifier identifier
Conditional code can be defined with the following syntax :
#if boolean expression
#if boolean expression
...
#else
...
#end
#else
#if boolean expression
...
#else
...
#end
#end
The boolean expression can use the following operators :
false
true
!expression
expression && expression
expression || expression
( expression )
Templated HTML code can be sent to a stream writer using the following syntax :
#write writer expression
<% code %>
<%@ natural expression %>
<%# integer expression %>
<%& real expression %>
<%~ text expression %>
<%= escaped text expression %>
<%! removed content %>
<%% ignored tags %%>
#end
--join
option requires to end the statements with a semicolon.#writer
directive is only available for the Go language.Install the DMD 2 compiler (using the MinGW setup option on Windows).
Build the executable with the following command line :
dmd -m64 generis.d
generis [options]
--prefix # : set the command prefix
--parse INPUT_FOLDER/ : parse the definitions of the Generis files in the input folder
--process INPUT_FOLDER/ OUTPUT_FOLDER/ : reads the Generis files in the input folder and writes the processed files in the output folder
--trim : trim the HTML templates
--join : join the split statements
--create : create the output folders if needed
--watch : watch the Generis files for modifications
--pause 500 : time to wait before checking the Generis files again
--tabulation 4 : set the tabulation space count
--extension .go : generate files with this extension
generis --process GS/ GO/
Reads the Generis files in the GS/
folder and writes Go files in the GO/
folder.
generis --process GS/ GO/ --create
Reads the Generis files in the GS/
folder and writes Go files in the GO/
folder, creating the output folders if needed.
generis --process GS/ GO/ --create --watch
Reads the Generis files in the GS/
folder and writes Go files in the GO/
folder, creating the output folders if needed and watching the Generis files for modifications.
generis --process GS/ GO/ --trim --join --create --watch
Reads the Generis files in the GS/
folder and writes Go files in the GO/
folder, trimming the HTML templates, joining the split statements, creating the output folders if needed and watching the Generis files for modifications.
2.0
Author: Senselogic
Source Code: https://github.com/senselogic/GENERIS
License: View license
1625055931
Hire top Indian front end developers for mobile-first, pixel perfect, SEO friendly and highly optimized front end development. We are a 16+ years experienced company offering frontend development services including HTML / CSS development, theme development & headless front end development utilising JS technologies such as Angular, React & Vue.
All our front-end developers are the in-house staff. We don’t let our work to freelancers or outsource to sub-contractors. Also, we have a stringent hiring mechanism to hire the top Indian frontend coders.
For more info visit: https://www.valuecoders.com/hire-developers/hire-front-end-developers
#front end developer #hire frontend developer #front end development company #front end app development #hire front-end programmers #front end application development
1619510796
Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.
Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is
Syntax: x = lambda arguments : expression
Now i will show you some python lambda function examples:
#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map
1653624773
Neste tutorial, você aprenderá do que se trata o PyScript e como usá-lo em arquivos HTML para executar o código Python no navegador. Você também aprende sobre as várias operações/funcionalidades que você pode fazer com o PyScript.
O Python cresceu imensamente em popularidade nos últimos anos. Possui uma ampla gama de aplicações, desde seu uso mais popular em Inteligência Artificial, até Ciência de Dados, Robótica e Scripting.
No campo de desenvolvimento web, o Python é usado principalmente no backend com frameworks como Django e Flask.
Até agora, o Python não tinha muito suporte no front-end, como outras linguagens, como JavaScript. Mas, felizmente, os desenvolvedores do Python construíram algumas bibliotecas (como Brython ) para oferecer suporte à sua linguagem favorita na web.
E este ano, durante a conferência PyCon 2022 , a Anaconda anunciou um framework chamado PyScript que permite usar Python na web usando HTML padrão.
Você precisará das seguintes ferramentas e conhecimento para codificar junto com este artigo:
Fonte: site oficial do PyScript
PyScript é uma estrutura de front-end Python que permite aos usuários construir programas Python usando uma interface HTML no navegador.
Ele foi desenvolvido usando o poder de Emscripten , Pyodide , WASM e outras tecnologias modernas da web para fornecer as seguintes habilidades de acordo com seus objetivos:
Fonte: Blog Anaconda
Nas últimas duas décadas, Python e linguagens de interface do usuário avançadas, como HTML, CSS e JavaScript modernos, não funcionaram em colaboração. O Python carecia de um mecanismo simples para criar interfaces de usuário atraentes para simplesmente empacotar e implantar aplicativos, enquanto HTML, CSS e JavaScript atuais podem ter uma curva de aprendizado íngreme.
Permitir que o Python utilize convenções de HTML, CSS e JavaScript resolve não apenas esses dois problemas, mas também aqueles relacionados ao desenvolvimento, empacotamento, distribuição e implantação de aplicativos da Web.
No entanto, o PyScript não deve assumir o papel de JavaScript no navegador – em vez disso, destina-se a fornecer aos desenvolvedores Python, principalmente cientistas de dados, mais flexibilidade e poder.
O PyScript oferece uma linguagem de programação com convenções de estilo consistentes, mais expressividade e facilidade de aprendizado, fornecendo o seguinte:
O PyScript é bastante fácil e direto de aprender. Para começar, você pode seguir as instruções no site ou baixar o arquivo .zip .
Neste artigo, usaremos e aprenderemos a usar o PyScript por meio do site . Você pode fazer isso vinculando os componentes em seu arquivo HTML. Vamos imprimir nosso primeiro “Hello World” com PyScript.
Para começar, você precisará criar um arquivo HTML para exibir texto em seu navegador usando o editor de texto/IDE de sua escolha.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Title: PyScript</title>
</head>
<body>
</body>
</html>
Depois de criar o arquivo HTML, precisaremos vincular o PyScript em seu arquivo HTML para ter acesso à interface PyScript. Isso será colocado na <head>
etiqueta.
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
Agora que você vinculou o PyScript ao arquivo HTML, você pode imprimir seu “Hello World”.
Você pode fazer isso com a <py-script>
etiqueta. A <py-script>
tag permite executar programas Python de várias linhas e imprimi-los na página do navegador. Coloque a etiqueta entre as <body>
etiquetas.
<body> <py-script> print("Hello, World!") </py-script> </body>
O código completo para o arquivo HTML está abaixo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Title: PyScript</title>
</head>
<body>
<py-script> print("Hello, World!") </py-script>
</body>
</html>
No seu navegador, você deve ver isso:
Dica: Se você estiver usando o editor VSCode, poderá usar o complemento Live Server no VSCode para recarregar a página à medida que atualiza o arquivo HTML.
Há mais operações que você pode realizar com a estrutura PyScript. Vejamos alguns deles agora.
Ao usar o PyScript, você pode querer passar variáveis do seu código Python para o HTML. Você pode fazer isso com o write
método do pyscript
módulo dentro da <pyscript>
tag. Usando o id
atributo , você passa strings exibidas como texto normal.
O método write aceita duas variáveis: o id
valor e a variável que será fornecida.
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<b><p>Today is <u><label id='today'></label></u></p></b>
<py-script>
import datetime as dt
pyscript.write('today', dt.date.today().strftime('%A %B %d, %Y'))
</py-script>
</body>
</html>
E a saída se torna:
O PyScript fornece uma interface para executar código Python em navegadores.
Para poder fazer isso, o PyScript usa a <py-repl>
tag. A <py-repl>
tag adiciona um componente REPL à página, que atua como um editor de código e permite escrever código executável embutido.
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<py-repl id="my-repl" auto-generate=true> </py-repl>
</html>
Experimentando no navegador (de preferência Chrome), você deve obter isto:
Uma das funções que o PyScript oferece é a flexibilidade. No PyScript você pode importar arquivos locais, módulos embutidos ou bibliotecas de terceiros. Este processo usa a <py-env>
tag. Esta tag é para declarar as dependências necessárias.
Para arquivos Python locais em seu sistema, você pode colocar o código em um .py
arquivo e os caminhos para os módulos locais são fornecidos na chave paths: na <py-env>
tag.
Vamos criar um arquivo Python example.py
para conter algumas funções:
from random import randint
def add_two_numbers(x, y):
return x + y
def generate_random_number():
x = randint(0, 10)
return x
Em seguida, o arquivo Python será importado para o HTML com a <py-env>
tag. Você deve colocar essa tag na <head>
tag, acima da <body>
tag.
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<py-env>
- paths:
- /example.py
</py-env>
</head>
<body>
<h1>Let's print random numbers</h1>
<b>Doe's lucky number is <label id="lucky"></label></b>
<py-script>
from example import generate_random_number
pyscript.write('lucky', generate_random_number())
</py-script>
</body>
</html>
Isso retornará:
Para bibliotecas de terceiros que não fazem parte da biblioteca padrão, o PyScript oferece suporte a elas.
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<py-env>
- numpy
- requests
</py-env>
</head>
<body>
<py-script>
import numpy as np
import requests
</py-script>
</body>
</html>
Você pode definir e configurar metadados gerais sobre seu aplicativo PyScript no formato YAML usando a <py config>
tag. Você pode usar esta tag neste formato:
<py-config>
- autoclose_loader: false
- runtimes:
-
src: "https://cdn.jsdelivr.net/pyodide/v0.20.0/full/pyodide.js"
name: pyodide-0.20
lang: python
</py-config>
Esses são os valores opcionais que a <py-config>
tag fornece. Eles incluem:
Neste artigo, você aprendeu sobre o que é o PyScript e como usá-lo em arquivos HTML para executar o código Python no navegador. Você também aprendeu sobre as várias operações/funcionalidades que você pode fazer com o PyScript.
Com o PyScript, é mais fácil executar e executar operações Python na web, pois isso não era fácil antes. Esta é uma ótima ferramenta para quem está ansioso para usar Python na web.
O PyScript ainda está em seus estágios iniciais e sob forte desenvolvimento. Ele ainda está em seu estágio alfa e enfrenta problemas conhecidos, como o tempo de carregamento, que pode afetar a usabilidade (algumas outras operações não podem ser exibidas no momento da redação deste artigo devido a problemas de desempenho). Portanto, você não deve usá-lo em produção ainda, pois provavelmente haverá muitas mudanças importantes.
Fonte do artigo original em https://www.freecodecamp.org
#pyscript #python