Skip to main content

Ferramenta para integração com o Google Services

Project description

Google Services

Biblioteca Python para integração genérica com os principais serviços do Google:
📧 Gmail, 📂 Google Drive, 📅 Google Calendar, 🔔 Google Pub/Sub e ☁️ Google Cloud Storage.

O diferencial é a autenticação unificada: você instancia uma vez a classe GoogleServicesAuth (suportando OAuth ou Service Account), e então acessa os serviços sem precisar reautenticar.


🚀 Pré-requisitos

  • Python 3.9+ (testado até 3.13)
  • Conta Google com APIs habilitadas no Google Cloud Console
  • Credenciais no formato OAuth Installed ou Service Account
  • (Opcional) Poetry para gerenciamento de dependências

📦 Instalação

Via pip:

pip install onedevcommongoogleservices

Via Poetry:

poetry add onedevcommongoogleservices

🔑 Autenticação

A classe GoogleServicesAuth aceita dois modos:

1. OAuth (Installed App)

from onedevcommongoogleservices import GoogleServicesAuth

credentials_json = {
    "installed": {
        "client_id": "seu_client_id",
        "project_id": "projeto_id",
        "auth_uri": "https://accounts.google.com/o/oauth2/auth",
        "token_uri": "https://oauth2.googleapis.com/token",
        "client_secret": "seu_client_secret",
        "redirect_uris": ["http://localhost"]
    }
}

auth = GoogleServicesAuth(
    credentials_json=credentials_json,
    allow_interactive=True  # abre o navegador na primeira vez
)

Depois da primeira autenticação, você pode salvar o token_json:

token_json = auth.creds.to_json()

E nas próximas vezes:

auth = GoogleServicesAuth(credentials_json, token_json=json.loads(token_json))

2. Service Account (com delegação opcional)

from onedevcommongoogleservices import GoogleServicesAuth

auth = GoogleServicesAuth(
    credentials_json=service_account_json,
    delegated_user="usuario@empresa.com"  # se usar Domain-Wide Delegation
)

📚 Exemplos de Uso

📧 Gmail

from onedevcommongoogleservices.gmail_service import GmailService

gmail = GmailService(auth)

# Listar últimos 10 e-mails
msgs = gmail.list_messages(limit=10)
print([m["id"] for m in msgs])

# Enviar e-mail
gmail.send_email(
    from_addr="meuemail@gmail.com",
    to="destinatario@empresa.com",
    subject="Teste",
    html_body="<h1>Olá</h1>",
    attachments=["/tmp/relatorio.pdf"]
)

📂 Google Drive

from onedevcommongoogleservices.drive_service import DriveService

drive = DriveService(auth)

# Criar ou substituir arquivo
drive.upload_or_replace_file(
    file_name="relatorio.pdf",
    mime_type="application/pdf",
    file_path="/tmp/relatorio.pdf",
    folder_id="id_da_pasta"
)

# Listar arquivos de uma pasta
files = drive.get_files_by_folder("id_da_pasta")
print(files)

📅 Google Calendar

from datetime import datetime, timedelta
from onedevcommongoogleservices.calendar_service import CalendarService

calendar = CalendarService(auth)

start = datetime.now() + timedelta(hours=1)
end = start + timedelta(hours=2)

event = calendar.create_event(
    summary="Reunião de Alinhamento",
    start=start,
    end=end,
    attendees=["joao@empresa.com"],
    conference_meet=True
)

print("Evento criado:", event["id"], event.get("hangoutLink"))

🔔 Pub/Sub

from onedevcommongoogleservices.pubsub_service import PubSubService

pubsub = PubSubService(auth)

# Criar tópico e subscription
topic_path = pubsub.ensure_topic("meu-projeto", "topico-teste")
sub_path = pubsub.ensure_subscription("meu-projeto", "sub-teste", topic_path)

# Publicar
pubsub.publish_json(topic_path, project_id=None, payload={"msg": "olá"})

# Consumir
msgs = pubsub.pull(sub_path, project_id=None, max_messages=5)
for ack_id, data, attrs in msgs:
    print("Mensagem:", data.decode())
    pubsub.ack(sub_path, [ack_id])

☁️ Google Cloud Storage (GCS)

from onedevcommongoogleservices.storage_service import GoogleCloudStorageService

# precisa incluir o escopo devstorage.read_write ao criar o auth
gcs = GoogleCloudStorageService(auth, default_bucket="meu-bucket")

# Upload de arquivo local
res = gcs.upload_file(
    source_path="/tmp/relatorio.pdf",
    dest_blob="relatorios/2025/relatorio.pdf",
    content_type="application/pdf",
)
print("Arquivo enviado:", res.name, res.public_url)

# Download
gcs.download_to_file(
    blob_name="relatorios/2025/relatorio.pdf",
    dest_path="/tmp/baixado.pdf"
)

# Listar arquivos
for f in gcs.list_files(prefix="relatorios/2025/"):
    print(f["name"], f["size"])

⚡ Funcionalidades

  • Autenticação unificada (OAuth Installed ou Service Account)

  • Token reutilizável (token_json)

  • ✅ Serviços prontos:

    • Gmail → listar, enviar e-mails, anexos
    • Drive → upload, busca, exclusão
    • Calendar → criar/listar eventos (com Google Meet)
    • Pub/Sub → tópicos, subscriptions, publish/pull
    • Cloud Storage → upload/download, listar, deletar, copiar/mover, URL assinada
  • ✅ Suporte a Domain-Wide Delegation para Service Accounts

  • ✅ Compatível com Poetry e pip


📝 Licença

Este projeto está sob a licença MIT.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

onedevcommongoogleservices-0.1.2.tar.gz (17.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

onedevcommongoogleservices-0.1.2-py3-none-any.whl (19.4 kB view details)

Uploaded Python 3

File details

Details for the file onedevcommongoogleservices-0.1.2.tar.gz.

File metadata

File hashes

Hashes for onedevcommongoogleservices-0.1.2.tar.gz
Algorithm Hash digest
SHA256 ba238a78c36972c32082d803892d08023d5aa6234cd1f88da1371aee28fe41d2
MD5 88ffc2f1b8712f0ce634de20711cefbd
BLAKE2b-256 acf39ca0e843462de5268121e430f4b6e5368474f9d44afc9e4320df4f00b341

See more details on using hashes here.

File details

Details for the file onedevcommongoogleservices-0.1.2-py3-none-any.whl.

File metadata

File hashes

Hashes for onedevcommongoogleservices-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 2df94a9aaca7e0f19ca33dcbfd1a8abf5b289a30e6c4f00891f6d77913864fc8
MD5 e554fdbc8fdde2cebc8f4fbe135a3393
BLAKE2b-256 8d9afd63af4a3cb8c52c134a760630262ae96e489b4682be6b311503f0300abf

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page