A decorator-based library for handling Google Cloud Pub/Sub messages with FastAPI integration, inspired by Micronaut's @PubSubListener
Project description
GCP PubSub Events
A modern, decorator-based Python library for Google Cloud Pub/Sub event handling. Inspired by event-driven architectures and frameworks like Micronaut, this library makes it easy to build scalable, event-driven microservices with minimal boilerplate.
Features
- Decorator-based API: Simple
@pubsub_listenerand@subscriptiondecorators - Type Safety: Full Pydantic model support with automatic validation
- Async Support: Works with both sync and async message handlers
- Framework Integration: Works seamlessly with FastAPI, Flask, Django
- Auto-retry Logic: Built-in retry mechanism with ack/nack support
- Resource Management: Optional automatic topic and subscription creation
- Comprehensive Testing: Well-tested with unit, integration, and e2e tests
Installation
pip install gcp-pubsub-events
Core Concepts
Decorators
@pubsub_listener: Marks a class as containing event handlers@subscription("subscription-name"): Marks a method as handling messages from a specific subscription
Message Acknowledgment
Every handler receives an Acknowledgement object:
ack.ack(): Message processed successfully, remove from queueack.nack(): Processing failed, retry later
Context Managers
The library provides context managers for lifecycle management:
pubsub_manager: Synchronous context managerasync_pubsub_manager: Asynchronous context manager for async frameworks
Basic Usage
from gcp_pubsub_events import pubsub_listener, subscription, PubSubManager
@pubsub_listener
class EventHandler:
@subscription("my-subscription")
def handle_message(self, data: dict, ack):
# Process the message
print(f"Received: {data}")
ack.ack()
# Create handler instance
handler = EventHandler()
# Use context manager for lifecycle management
with PubSubManager("my-project-id") as manager:
# Application runs here
# Manager handles all setup and cleanup
pass
FastAPI Integration
from contextlib import asynccontextmanager
from fastapi import FastAPI
from gcp_pubsub_events import async_pubsub_manager, pubsub_listener, subscription
@pubsub_listener
class MyService:
@subscription("my-subscription")
async def handle_event(self, data: dict, ack):
# Process event
ack.ack()
@asynccontextmanager
async def lifespan(app: FastAPI):
# Create service instance first
service = MyService()
# Then start the manager
async with async_pubsub_manager("my-project") as manager:
yield
app = FastAPI(lifespan=lifespan)
Configuration
Environment Variables
# Required
export GOOGLE_CLOUD_PROJECT="my-project-id"
# Optional
export PUBSUB_EMULATOR_HOST="localhost:8085" # For local development
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json"
Manager Configuration
from gcp_pubsub_events import PubSubManager
manager = PubSubManager(
project_id="my-project",
max_workers=10, # Thread pool size
max_messages=100, # Max concurrent messages
auto_create_resources=True, # Auto-create topics/subscriptions
clear_registry_on_start=False # Clear handlers on restart
)
Testing
The library includes comprehensive test support:
# Run all tests
poetry run pytest
# Run with emulator
export PUBSUB_EMULATOR_HOST=localhost:8085
gcloud beta emulators pubsub start
poetry run pytest tests/integration/
Contributing
We welcome contributions! Please see our Contributing Guide for details.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Resources
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file gcp_pubsub_events-2.0.0.tar.gz.
File metadata
- Download URL: gcp_pubsub_events-2.0.0.tar.gz
- Upload date:
- Size: 17.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.17
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c80e58715af67ff91348f47499761c9fa4573b337234e92f5c654fe6580d3149
|
|
| MD5 |
773e598b4e19925167813edf05907c8e
|
|
| BLAKE2b-256 |
6214a91ea50455543f12693b69fdbad5b7f8b175f84336cee5924a4b2485339b
|
File details
Details for the file gcp_pubsub_events-2.0.0-py3-none-any.whl.
File metadata
- Download URL: gcp_pubsub_events-2.0.0-py3-none-any.whl
- Upload date:
- Size: 20.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.17
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9f699b15e9e319b3f53543e5f9483bfa8f0808b2228a96ece38c1dc3abbe8151
|
|
| MD5 |
010fc70bc98747a4faa85c517544ede5
|
|
| BLAKE2b-256 |
7facde04ba4ba58c2a11f8547e34b837c2ee63c29494d4d0f42113fdc268e7a3
|