Tutorial para iniciantes no Ray, o novo framework de Python

A cada dia, a tecnologia avança para novas profundidades. Novos frameworks, bibliotecas, padrões de design surgem para acompanhar a taxa de inovação em outros setores. Plataformas sociais de codificação como Livecoding.tv, GitHub, StackOverFlow, etc, são ótimos termômetros para ver quais novas tecnologias estarão em voga.

Uma dessas novas tecnologias é o Ray, um framework para Python desenvolvido por Felipe Volpone, um programador brasileiro, e a impressão inicial parece promissora. Também deve ser observado que o Ray foi feito com inspiração no Django e no Flask, de modo a ser possível criar poderosas REST APIs. Neste artigo, vamos nos concentrar em explorar as diferentes características do framework Ray e também construir um blog simples usando o framework.

Antes de começar, vamos analisar as principais características do framework Ray:

  • Desenvolvimento de API com o Ray é fácil e divertido;
  • Vem com o servidor interno uWSGI para fins de hospedagem;
  • É compatível com Pewee, Google App Engine e SQLAlchemy;
  • Oferece Proteção API;
  • Ganchos de banco de dados e ações em APIs também são suportados;
  • Suporta autenticação.

Instalando o Ray

Para usar o Ray, você precisa instalar o software de pré-requisito e bibliotecas para torná-lo funcional. Para um bom funcionamento e instalação, é necessário instalar o seguinte:

  • Peewee ORM;
  • Ray Framework;
  • Ray Peewee.

Para fazer isso, você precisa executar os seguintes comandos pip no seu terminal Linux. (Ubuntu 16.04 é usado para o tutorial).

pip install peewee

pip install ray_framework

pip install ray_peewee

Nota: Certifique-se de executar comandos usando sudo ou uma conta root.

Criando o App.py para o modelo de postagem

A criação de um modelo irá assegurar que as postagens sejam exibidas corretamente e interajam com o banco de dados. Para fazer isso, precisamos criar um arquivo “app.py” com o modelo de postagem. Verifique o código abaixo sobre como abordá-lo:

app.py

# app.py

import peewee

from ray_peewee.all import PeeweeModel

from ray.wsgi.wsgi import application

from ray.endpoint import endpoint

database = peewee.SqliteDatabase('example.db')

class DBModel(PeeweeModel):

class Meta:

database = database

@endpoint('/post')

class Post(DBModel):

title = peewee.CharField()

description = peewee.TextField()

database.create_tables([Post])

Depois de feito, você precisa executar o aplicativo usando o seguinte comando:

ray up --wsgifile=app.py

# if you're using virtualenv

ray up --wsgifile=app.py --env <env_dir>

Não estamos usando um virtualevn, então você pode usar o primeiro comando para executar o servidor. Agora você pode acessar o servidor digitando localhost: 8080 na barra de endereços.

Como não temos nenhum recurso ou dados configurados, ele dará um erro 404.

Agora iremos em frente e criar um post usando o método CURL.

curl -X POST -H "Content-Type: application/json" -d '{

"title": "New blog!",

"description": "let’s do this"

}'"http://localhost:8080/api/post"

Você pode usar os seguintes métodos CURL para interagir com seu blog:

Listar todas as postagens no blog: curl -X GET “http://localhost:8080/api/post/”

Recuperar uma postagem: curl -X GET “http://localhost:8080/api/post/1”

Gravar pesquisa: curl -X GET “http://localhost:8080/api/post?name=john”

Atualizar postagem usando CURL: curl -X PUT -H “Content-Type: application/json” -d ‘{“title”: “let’s change the title.”}'”http://localhost:8080/api/post/1″

Excluir uma postagem: curl -X DELETE “http://localhost:8080/api/post/1”

Pronto! Você configurou com êxito o seu blog usando o framework Ray. Você pode ler mais sobre os recursos do Ray como Endpoints, ganchos, autenticações, etc., nestes artigos do Medium e do blog do Livecoding.tv.

Comente e deixe-nos saber o que achou deste tutorial. Além disso, compartilhe seus pensamentos sobre como você acha que o framework Ray pode afetar o desenvolvimento web em Python.

Dr. Michael J. Garbade

I, Dr. Michael J. Garbade is the co-founder of the Education Ecosystem (aka LiveEdu), ex-Amazon, GE, Rebate Networks, Y-combinator. Python, Django, and DevOps Engineer. Serial Entrepreneur. Experienced in raising venture funding. I speak English and German as mother tongues. I have a Masters in Business Administration and Physics, and a Ph.D. in Venture Capital Financing. Currently, I am the Project Lead on the community project -Nationalcoronalvirus Hotline I write subject matter expert technical and business articles in leading blogs like Opensource.com, Dzone.com, Cybrary, Businessinsider, Entrepreneur.com, TechinAsia, Coindesk, and Cointelegraph. I am a frequent speaker and panelist at tech and blockchain conferences around the globe. I serve as a start-up mentor at Axel Springer Accelerator, NY Edtech Accelerator, Seedstars, and Learnlaunch Accelerator. I love hackathons and often serve as a technical judge on hackathon panels.

View Comments

Recent Posts

Highest Stable Coin Yields – (W16 – 2024)

Another week to bring you the top yield platforms for three of the most prominent…

2 weeks ago

LEDU Token OTC Trading

If you hold a large volume of LEDU tokens above 1 million units and wish…

1 month ago

Highest Stable Coin Yields – (W12 – 2024)

It’s another week and like always we have to explore the top yield platforms for…

1 month ago

Binance Auto Invest – the Best Innovation in Crypto since Sliced Bread

At a time where we’re constantly seeking tools and strategies to simplify our crypto investments,…

1 month ago

Highest Stable Coin Yields – March 2024

As we kick off another week, it's time to explore the top yield platforms for…

2 months ago

Education Ecosystem Featured on Business Insider

We're excited to share that Education Ecosystem was recently featured in an article on Business…

2 months ago