Skip to main content

sagecoders-events

SDK Python de SageEvents, le bus d'événements de l'écosystème SageCoders. Il ne dépend d'aucun framework : Django, FastAPI, Flask ou script. Il signe exactement comme le SDK JS @sagecoders/events : un test commun le garantit.

pip install sagecoders-events
Fonction Rôle
SageEvents(url, token, app) Client. token : jeton de compte de service SageAuth, ou fonction qui le renvoie
.publish(type, data, org_id=, subject_id=, correlation_id=, causation_id=, sensitive=, id=) Publier un événement
.subscribe(endpoint, patterns, secret=None) Déclarer l'URL de livraison et les motifs écoutés ; renvoie le secret de signature
handle(raw_body, signature_header, secret, fn) Recevoir une livraison : vérifie la signature, appelle fn(event), renvoie le statut, les en-têtes et le corps à répondre
verify_signature(raw_body, header, secret) Vérifier seulement la signature (corps brut)
matches(pattern, type), uuid7() Motifs d'abonnement, identifiants

Toutes les erreurs sont des SageEventsError avec un code stable et un status HTTP.

Publier

from sagecoders_auth import ServiceAccount
from sagecoders_events import SageEvents

svc = ServiceAccount(issuer=SAGEAUTH_ISSUER, key=SAGEAUTH_SERVICE_KEY_B64, sageauth_project_id=SAGEAUTH_ADMIN_PROJECT_ID)
bus = SageEvents(SAGE_EVENTS_URL, token=lambda: svc.get_token(SAGE_EVENTS_PROJECT_ID), app="sage-hotel")

bus.publish(
    "sagehotel.booking.created",
    {"reservation_id": "R-1", "guest_phone": "+2250700000000"},
    org_id="org_ivoire",
    subject_id="R-1",
    sensitive=["data.guest_phone"],   # masqué dans la console sans permission
)

Le type est au format produit.objet.action, dans l'espace de noms de votre projet SageAuth. SageEvents vérifie le droit de publier auprès de SageAuth.

Pour publier en réaction à un événement reçu, reprenez son correlation_id et passez son id en causation_id. La console reconstruit ainsi l'arbre complet de l'action.

S'abonner (au déploiement)

r = bus.subscribe("https://api.sagehotel.com/sageevents/", ["sagecoders.user.deleted", "sagestock.*"])
SAGE_EVENTS_SECRET = r["secret"]   # à garder dans le coffre de secrets

Recevoir

Chaque livraison est un POST signé (SageEvents-Signature). Votre fonction renvoie PROCESSED (ou None), ou IGNORED si l'événement ne vous concerne pas. Une exception déclenche une nouvelle tentative (5 s, 15 s, 1 min… puis lettre morte, rejouable depuis la console).

from sagecoders_events import IGNORED, handle

def traiter(event):
    if event["type"] != "sagecoders.user.deleted":
        return IGNORED
    delier_compte(event["data"]["sub"])

Django

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

@csrf_exempt
@require_POST
def sageevents(request):
    r = handle(request.body, request.headers.get("SageEvents-Signature"), settings.SAGE_EVENTS_SECRET, traiter)
    response = HttpResponse(r.body, status=r.status)
    for k, v in r.headers.items():
        response[k] = v
    return response

FastAPI

from fastapi import Request, Response

@app.post("/sageevents/")
async def sageevents(request: Request):
    r = handle(await request.body(), request.headers.get("SageEvents-Signature"), SAGE_EVENTS_SECRET, traiter)
    return Response(r.body, status_code=r.status, headers=r.headers)

Flask : r = handle(request.get_data(), request.headers.get("SageEvents-Signature"), SECRET, traiter), puis return r.body, r.status, r.headers.

Passez toujours le corps brut, avant tout décodage JSON. Répondez en moins de 10 s ; un traitement long va dans une file.

Développement

python -m venv .venv && .venv/Scripts/pip install -e .     # (bin/ sous Linux et macOS)
python -m unittest discover -s tests                       # hors ligne, SageEvents simulé

Metadata

Release files for sagecoders-events 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for sagecoders-events 0.1.0
File Size Uploaded Provenance Actions
sagecoders_events-0.1.0.tar.gz 7.4 kB Without provenance Details for sagecoders_events-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for sagecoders-events 0.1.0
File Interpreter ABI Platform Actions
sagecoders_events-0.1.0-py3-none-any.whl Python 3 none any Details for sagecoders_events-0.1.0-py3-none-any.whl

Total release size: 15.2 kB

Release files / sagecoders_events-0.1.0.tar.gz

Download URL sagecoders_events-0.1.0.tar.gz
Size 7.4 kB
Tags Source
SHA-256 checksum
How to use checksums
f3bb7d2615dd3a5ac555708d3dbe4dd02825e67bd9c6cb28865cc0a8e8e3eae9
BLAKE2b-256 checksum
How to use checksums
c2efc9b9d398016ee56d679e32392a886ff90424c5b657a8d755fb15d3955822
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.9

Release files / sagecoders_events-0.1.0-py3-none-any.whl

Download URL sagecoders_events-0.1.0-py3-none-any.whl
Size 7.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
56e134ecc75e600b8d6c5a6588c3f4b4f81c1ab37ca2c18e6fbb802c023c8a3c
BLAKE2b-256 checksum
How to use checksums
a570fde062fb63f4c8fb0ecaa4ea133e0782543a26928f441251b78c8b7acb6f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.9

Security for sagecoders-events 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page