Skip to main content

Uma coleção de utilitários para acelerar o desenvolvimento backend em Python com padrões reutilizáveis e produtivos

Project description

🐍 SnakeStack

Python built with uv Pipeline PyPI version License: MIT codecov gitleaks badge


📦 Visão Geral

O snakestack é um pacote modular que oferece uma base robusta para construção de serviços backend com foco em:

  • Observabilidade com OpenTelemetry
  • Cache assíncrono com Redis
  • Integração com Google Pub/Sub
  • Acesso assíncrono ao MongoDB
  • Client HTTPX com suporte a tracing
  • Modelos base com pydantic e pydantic-settings
  • Stack de logging estruturado e configurável

⚙️ Instalação

Base

pip install snakestack

Extras disponíveis

Extra Comando de instalação
Redis pip install snakestack[redis]
MongoDB pip install snakestack[mongodb]
Pub/Sub pip install snakestack[pubsub]
Telemetry pip install snakestack[telemetry]
Retry pip install snakestack[retry]
Todos pip install snakestack[all]

📚 Módulos disponíveis

Módulo Descrição Extra
snakestack.logging Logging estruturado com filtros, formatadores e propagação de request ID
snakestack.cache Cliente Redis assíncrono com TTL, prefixo e serialização via orjson [redis]
snakestack.pubsub Publisher e subscriber para Google Pub/Sub com presets e tracing [pubsub]
snakestack.telemetry Setup do OpenTelemetry com auto-instrumentação de HTTPX e logging [telemetry]
snakestack.mongodb Wrapper assíncrono para PyMongo com singleton de conexão [mongodb]
snakestack.healthz Agregador de health checks com medição de latência por check
snakestack.httpx AsyncClient do HTTPX com composição de URL e normalização de erros
snakestack.model Modelos base Pydantic v2: StrictModel, LenientModel, ORMModel
snakestack.task Pool de workers assíncrono sobre asyncio.Queue com shutdown graceful
snakestack.retry Decorator de retry para APIs externas com backoff exponencial, logging e tracing [retry]
snakestack.config Gerenciamento de settings com pydantic-settings

🧪 Exemplos de Uso

Os exemplos completos estão no diretório examples/.

Cache

Arquivo Descrição
cache/async_cache_service.py Uso básico do AsyncRedisService com diferentes tipos de valor

Healthz

Arquivo Descrição
healthz/sample_healthz.py Health check com callbacks síncronos e assíncronos
healthz/sample_healthz_with_deps.py Health check verificando Redis e MongoDB

HTTPX

Arquivo Descrição
httpx/sample_use_httpx.py Client HTTPX básico com composição de URL
httpx/sample_use_httpx_with_telemetry.py Client HTTPX com tracing via OpenTelemetry

Logging

Arquivo Descrição
logging/default_logging.py Formatter padrão
logging/with_request_id_logging.py Formatter com propagação de request ID
logging/custom_json_logging.py Formatter JSON estruturado
logging/excluded_name_filter_logging.py Filtro por nome do logger
logging/filter_path_logging.py Filtro por path da requisição

MongoDB

Arquivo Descrição
mongodb/sample_mongodb.py Conexão, consulta e encerramento com PyMongo assíncrono

Pub/Sub

Arquivo Descrição
pubsub/sample_publisher.py Publicação básica de mensagens
pubsub/sample_publisher_with_open_telemetry.py Publicação com tracing
pubsub/sample_subscriber.py Subscriber com SimpleProcessor
pubsub/sample_subscriber_with_batch.py Subscriber com BatchProcessor
pubsub/sample_subscriber_with_open_telemetry.py Subscriber com tracing
pubsub/sample_flow_control.py Configuração de flow control

Settings

Arquivo Descrição
settings/sample_settings.py Uso do SnakeStackSettings com override por env var

Task

Arquivo Descrição
task/sample_task.py Worker pool básico
task/sample_task_with_sentinel.py Worker pool com sentinel de encerramento
task/sample_task_with_callback.py Worker pool com callback customizado

Retry

Arquivo Descrição
retry/sample_with_logging.py Retry com logging estruturado em chamadas a APIs externas
retry/sample_with_telemetry.py Retry com eventos de tracing via OpenTelemetry

Telemetry

Arquivo Descrição
telemetry/sample_telemetry.py Setup do OpenTelemetry com instrument_app
telemetry/sample_decorator_telemetry.py Tracing via decorator @instrumented_span

🛠️ Desenvolvimento Local

1. Clone o repositório

git clone https://github.com/BrunoSegato/snakestack.git
cd snakestack

2. Instale as dependências

uv sync --all-groups --all-extras

3. Instale os hooks de pre-commit

make hooks

4. Suba os serviços locais

docker-compose up -d

🧾 Comandos

Comando Descrição
make install Instala apenas dependências de runtime
make lint Executa ruff check
make format Executa ruff check --fix
make mypy Executa mypy sem cache incremental
make check Executa lint + mypy
make pre-commit Executa todos os hooks de pre-commit
make test Executa todos os testes
make test-unit Executa apenas testes unitários
make test-matching test=nome Executa testes por nome com -vv -s --pdb
make release Bump de versão + changelog via commitizen
make publish Publica no PyPI

🧪 Testes

O projeto possui cobertura completa de testes unitários organizados por domínio.

# Todos os testes
make test

# Apenas testes unitários
make test-unit

# Testes de um domínio específico
uv run pytest -m cache
uv run pytest -m pubsub
uv run pytest -m telemetry
uv run pytest -m mongodb
uv run pytest -m retry

# Teste por nome
make test-matching test='nome_do_teste'

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

snakestack-0.36.1.tar.gz (34.5 kB view details)

Uploaded Source

Built Distribution

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

snakestack-0.36.1-py3-none-any.whl (49.3 kB view details)

Uploaded Python 3

File details

Details for the file snakestack-0.36.1.tar.gz.

File metadata

  • Download URL: snakestack-0.36.1.tar.gz
  • Upload date:
  • Size: 34.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.8.6

File hashes

Hashes for snakestack-0.36.1.tar.gz
Algorithm Hash digest
SHA256 5afd94cb0f134151a6dfaf7bf7c0127485c96e01f0c0a7a536331a1ddbbbedb8
MD5 81308406ac86e117f4431faea0cf21b6
BLAKE2b-256 4aea58aa6ad8b18916dc85f32c0a65b2794da8ee4f1ff99b3486fbde3c1b9e7d

See more details on using hashes here.

File details

Details for the file snakestack-0.36.1-py3-none-any.whl.

File metadata

File hashes

Hashes for snakestack-0.36.1-py3-none-any.whl
Algorithm Hash digest
SHA256 09e51f9a18696ed6bfc2ce903455720c28c817219ebe346ba4fbf554c55191ae
MD5 eea392cac4c8ae40486a673360da99aa
BLAKE2b-256 8072a7e287a3b971b96b700dbe277733fef11c64c6bb308313c2fdd53a16050e

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