cent
Python SDK for the HTTP server API
of Centrifugo: every API method,
including those of Centrifugo PRO, in a blocking Client and an async
AsyncClient; connection, subscription and server API tokens; the proxy
handlers and the endpoints client SDKs call. For a real-time client over
WebSocket, see centrifuge-python.
pip install cent # httpx2 is the only dependency
pip install cent[crypto] # RSA, ECDSA and Ed25519 tokens, with cryptography
| Version | |
|---|---|
| Python | 3.11 or newer |
| Centrifugo | v6, any release |
| Map and shared poll methods | Centrifugo v6.8.0 or newer |
ApiError.temporary, TooManyRequestsError, refused requests reported as such rather than as internal errors |
Centrifugo v6.10.0 or newer |
Ed25519 tokens verified without JWKS, by client.token.ed25519_public_key |
Centrifugo v6.10.2 or newer |
| Methods marked "Centrifugo PRO only" | Centrifugo PRO v6 |
cent 6 replaces cent 5: see MIGRATING.md. cent implements the Centrifugo server SDK specification, version 0.4.
Example
import os
import cent
client = cent.Client("http://localhost:8000/api", api_key=os.environ["CENTRIFUGO_API_KEY"])
res = client.publish(channel="news", data={"text": "hello"})
print(f"published at offset {res.offset}")
And from asyncio code, the same methods awaited:
async with cent.AsyncClient("http://localhost:8000/api", api_key=key) as client:
await client.publish(channel="news", data={"text": "hello"})
Every API method takes its request's fields as keyword arguments - generated
from Centrifugo's api.proto, each documented - and returns its result, a
dataclass, raising unless Centrifugo did everything asked. A batch and
commands have the same methods: batch.publish(...), cent.command.publish(...).
A field the protos mark required is a required argument, of the method and of
a nested type alike - cent.DeviceTopicsUpdate(op=...) - and is checked for a
value before sending: channel="", given empty, raises InvalidRequestError
naming it, limit_strategy.rate_limit.policies[0].rate for a nested one, as a
missing one would - an empty value is not sent. The fields whose empty value
means something are sent empty: invalidate_user_tokens(user="") is anonymous
users, and device_update's user_update=cent.DeviceUserUpdate(user="")
detaches the devices from their user, as an empty timezone, locale or meta
update clears it; an update left None changes nothing. Any other nested
message with nothing set is not sent.
A string field with a fixed set of values has a constant per value, generated
from the protos: cent.PROVIDER_FCM, cent.PLATFORM_IOS, cent.OP_ADD,
cent.STATUS_DELIVERED, cent.KEY_MODE_IF_NEW, cent.CMP_EQ and
cent.FILTER_NODE_OP_AND for a filter's op - the names the spec pins for
every SDK. The fields stay str: a value Centrifugo added since
is still sent.
Create the client once and share it: it is safe for concurrent use. An
AsyncClient belongs to the event loop of its first call - one per loop, so
not across asyncio.run calls; in code which is not async use Client. A
Client used in a process forked after its first call, under a pre-forking
server say, starts its own connections there.
cent.to_dict(res) turns a result - a broadcast's, a batch's or an error, too
- into a dict of JSON values with Centrifugo's field names, for a response of
your own:
json.dumps(cent.to_dict(res)).
Payloads
data, info, meta and the other payloads are JSON values, given as the
Python values they decode to - dict, list, str, int, float, bool,
None - and returned the same way: a payload from a reply sent back unchanged
is the same JSON value. A str is a JSON string. JSON you already have, or
encode with rules of your own, goes in cent.RawJSON, sent as it is:
client.publish(channel="news", data=cent.RawJSON(row.payload_json))
A payload which is not JSON - NaN, bytes, a set - raises InvalidRequestError
before anything is sent. Binary data goes base64-encoded in the b64 fields,
such as b64data.
Write integers which may pass 2^53 - a 64-bit ID, say - as JSON strings: browsers and JavaScript backends decode JSON numbers as doubles, and round larger integers silently.
Pages and stream positions
history_all, device_list_all, device_topic_list_all, user_topic_list_all
and map_read_state_all take the arguments of their method and return the
items of every page - a generator, an async iterator on AsyncClient - reading
a page when the loop reaches it; leaving the loop early reads no further page:
for device in client.device_list_all(filter=cent.DeviceFilter(users=["42"]), limit=100):
...
async for pub in aclient.history_all(channel="news", limit=100):
...
history_all pages by since and refuses a limit below 1 and reverse at
the call. It yields cent.HistoryItems - each a Publication, pub.data and
pub.offset as ever, with position() to resume from:
for pub in client.history_all(channel="news", limit=100, since=last):
handle(pub.data)
last = pub.position()
map_read_state_all yields cent.MapStateItems - each a MapEntry, with
state, the position the state was read at, which map_read_stream follows
it from. map_read_state_all reads every page after the first at the first
one's revision, so that a map reset between pages raises
UnrecoverablePositionError instead of mixing two states: read again from the
start then. What a paged method lists changes under the iteration: a device
registered while listing may or may not be seen. An iteration lasts as long
as your loop, so the iterators take no timeout: page_timeout bounds each
page's request, replacing request_timeout for it, as attempt_timeout does
for a retry's attempt. Cancelling the task, or an asyncio.timeout around the
loop, ends the iteration.
Every result holding an offset and epoch - publish's, history's,
map_read_state's, map_read_stream's, map_publish's and map_remove's -
gives them as position(), a cent.StreamPosition - what came after
a publication is history's since:
res = client.publish(channel="news", data={"text": "hi"})
later = client.history(channel="news", limit=100, since=res.position())
A position whose epoch is no longer the stream's raises
UnrecoverablePositionError: the stream was reset, and reading from its start
is the only recovery. map_read_stream takes a position apart:
since_offset=pos.offset, since_epoch=pos.epoch.
Timeouts
request_timeout - ten seconds by default - bounds every call. A call's own
timeout, in seconds, replaces it for that call, longer or shorter:
client.info(timeout=0.5)
The timeout bounds the call: connecting, each read and write, and the reply's
body, which is checked against it as it arrives. However a call times out, it
raises cent.CentTimeoutError, which is also a builtin TimeoutError. A
blocking call can outlast its timeout in one case only: a server - a proxy in
trouble, say - sending the reply's headers a few bytes at a time, each read
within the timeout. AsyncClient bounds the whole call, that case included.
In asyncio code an asyncio.timeout() around a call, or cancelling its task,
ends it sooner, but never later: a call under a longer deadline still gives
up on a stuck Centrifugo after request_timeout.
broadcast_with_retry makes several requests in one call: its timeout
bounds them all, waits between them included, and attempt_timeout is each
one's own timeout, replacing request_timeout for it, longer or shorter,
while timeout still ends an attempt sooner.
Errors
| Exception | Meaning |
|---|---|
cent.ApiError |
Centrifugo refused the request or failed to carry it out: code, message, temporary. Known codes are subclasses: UnknownChannelError, NotFoundError, BadRequestError, NotAvailableError, TooManyRequestsError, InternalError... |
cent.BroadcastFailedChannelsError, cent.BatchFailedCommandsError |
some parts of a broadcast or batch failed - see below |
cent.HTTPError |
the request did not reach the API method: status_code, body, headers; UnauthorizedError for rejected credentials |
cent.DecodeError |
the reply was not Centrifugo's - usually api_endpoint points elsewhere |
cent.InvalidRequestError |
the client could tell the request is wrong and did not send it |
cent.InvalidConfigError |
the client refuses to work as configured - not created, used from a second event loop, or given an endpoint or token by api_endpoint_func or bearer_token_func which it cannot send: the message names the option and the fix |
cent.FunctionError |
api_endpoint_func or bearer_token_func raised: the message names the function, its exception is the __cause__, and retryable judges it by that |
cent.NetworkError, cent.CentTimeoutError, cent.ClosedError |
as their names say |
All are cent.CentError. Centrifugo adds error codes over time: an unknown code
is still an ApiError, so match the codes you handle and treat the rest by
class.
Retries
cent.retryable(err) reports whether a new attempt, with time left, may
succeed: the error came from a temporary condition - a broker being
unavailable, a rate limit, the network - not from the request.
A temporary error does not mean nothing was done: after a timeout, or even an
internal error, the publication may have happened. So retry a publication only
with an idempotency_key, and back off between a bounded number of attempts:
request = dict(
channel="orders:42",
data=data,
# The same key on every attempt: a publication which happened in an
# earlier attempt, even one reported as failed, is not published again.
idempotency_key="order-42-paid",
)
backoff = cent.exponential_backoff(0.2, 5.0)
for attempt in itertools.count(1):
try:
client.publish(**request)
break
except cent.CentError as e:
if not cent.retryable(e) or attempt == 3:
raise
time.sleep(backoff(attempt)) # await asyncio.sleep(...) in async code
Choosing keys:
- One key per publication or broadcast, reused only to retry that same one. A broadcast needs one key, not one per channel.
- Centrifugo remembers a key per channel, for five minutes by default. A retry
within that time is answered with the first result and not published again -
and so is a different publication into the same channel under the same
key. A key built from an ID must name the event too:
order-42-paid, notorder-42. - The memory, Redis and PostgreSQL brokers keep keys. The NATS broker ignores them, so with it a retry publishes again.
Retry a broadcast with broadcast_with_retry rather than a loop: see below.
Broadcast and batch
broadcast publishes the same data into many channels in one request; a batch
sends many commands at once. Both raise unless every part succeeded:
client.broadcast(channels=["user:1", "user:2"], data={"text": "hello"}, idempotency_key=message_id)
batch = client.new_batch()
pub = batch.publish(channel="news", data=data)
stats = batch.presence_stats(channel="news")
batch.send()
pub.result() # each command has its own result, or raises its own error
stats.result()
Parts succeed or fail on their own. When Centrifugo carried the request out
and some parts failed, up to all, it raises BroadcastFailedChannelsError or
BatchFailedCommandsError: its failed lists them, and its result holds
every part's outcome. Any other exception means the request failed as a whole
- the network, the credentials, an invalid request - and no part got a reply; after a timeout or a network error Centrifugo may still have carried it out.
A partial error is not an error of its parts: except UnknownChannelError does
not catch a broadcast in which a channel was unknown, nor one into a single
channel - use publish for one channel. To go on despite some failed parts:
try:
client.broadcast(channels=channels, data=data)
except cent.BroadcastFailedChannelsError as e:
log.warning("broadcast failed in %s", e.result.failed)
Retrying:
-
a broadcast:
broadcast_with_retrydoes it. It sends again only the channels which may still succeed, all attempts with oneidempotency_key- made for the call when the request has none - and returns every channel's last outcome, asbroadcastdoes:res = client.broadcast_with_retry(channels=channels, data=data, max_attempts=5, attempt_timeout=2, timeout=10)
By default it retries once, after about 100 milliseconds.
on_attempt_erroris called after each failed attempt which will be retried, with the channels to retry and their errors: it returns the seconds to wait before the next attempt - orNonefor the default backoff - and may log or count meanwhile; it raises to stop. AHTTPErrorina.errorcarries the response'sheaders: wait at least itsRetry-Afterto honour one.backoff = cent.exponential_backoff(0.2, 5.0) def on_attempt_error(a: cent.BroadcastAttempt) -> float: log.info("attempt %d: %d channels to retry", a.attempt, len(a.retry)) return backoff(a.attempt)
res.idempotency_keyis the key the attempts used: to retry the broadcast later, after it gave up - from a job queue, say - send it with that key. Repeatingbroadcaston any error would instead send it to every channel again, those which already got it included. -
a batch: build a new one, with the same keys, from the commands
e.failedlists with a retryable error. A batch is sent once.
new_batch() runs the commands one by one, in order; parallel=True runs them
concurrently. Centrifugo PRO sends a batch's publications to its broker
together: each channel's publications still take effect in order, but
publications into different channels may not, unless the namespace sets
publication_grouping_disabled.
Automatic batching
With auto_batch, calls made concurrently from one process go out together
once max_in_flight requests are in flight, with no delay otherwise, since
nothing waits for a timer. It is for processes which publish a lot at once - an
asyncio server or worker with many tasks publishing, a thread pool fanning
publications out - and does nothing for a sync web worker of a few threads:
leave it off there.
client = cent.AsyncClient(endpoint, api_key=key, auto_batch=cent.AutoBatch(max_in_flight=8))
Set max_in_flight to about half the tasks or threads which call the client
at once. It batches only calls made while that many requests are in flight:
above the concurrency, it never does; just below, it batches calls one at a
time, and only limits them. Under heavy publishing it sends a fraction of the
requests, and Centrifugo does about half the work per publication.
Every call still gets its own result or error, and keeps its own deadline, the
one it would have alone. The batch request lasts until the latest of its
calls' deadlines, and at least request_timeout from when it is sent, so it
may outlast a call which gave up while it was in flight. Calls
sharing a batch share its request, though: if the request itself fails - the
network, a body too large for a proxy in front of Centrifugo - every call in it
fails.
A batch belongs to no single caller: it runs in a context of its own, which
carries no caller's contextvars. batch_context makes it one from the
callers' contexts - for a tracing span linking each caller's span:
def batch_context(callers: list[contextvars.Context]):
links = [trace.Link(c.run(trace.get_current_span).get_span_context()) for c in callers]
return tracer.start_as_current_span("cent batch", links=links)
client = cent.Client(endpoint, api_key=key, auto_batch=cent.AutoBatch(max_in_flight=8), batch_context=batch_context)
Authentication
api_key is sent in the X-API-Key header. bearer_token_func instead sends a
token as Authorization: Bearer, for Centrifugo PRO's JWKS authentication - it
is called for every request, so return a cached token. Leave both unset when
mutual TLS, set up in http_client, or a proxy authenticates instead.
To sign the tokens yourself, token.APITokenSource issues them and reuses each for
half its lifetime:
from cent import token
api_tokens = token.APITokenSource(
key=api_key, # its own key - never one of the client tokens
claims=token.APIClaims(audience="centrifugo-api", scope=["centrifugo:api"]),
)
client = cent.Client("https://centrifugo.example.com/api", bearer_token_func=api_token_source.token)
Centrifugo PRO accepts a token signed with any key of http_api.jwks.endpoint,
and checks the audience, issuer and scope only when configured to. So keep API
tokens apart from the connection and subscription tokens your users hold - or
any user can call the server API with their connection token:
- publish the API keys with
endpoints.JWKS(*api_keys)at an endpoint of their own, not the one ofclient.token.jwks_public_endpoint; - set
http_api.jwks.audienceandhttp_api.jwks.scopeto values only API tokens carry -token.apirefuses claims with neither.
The API keys rotate as client keys do: see Key rotation with JWKS.
Rejected credentials make every call raise cent.UnauthorizedError.
HTTP client, tracing and metrics
cent sends requests with httpx2, the
maintained fork of httpx: the same API, imported as httpx2. Without
http_client, a client keeps its connections alive between calls and never
follows redirects. A client you
pass - an httpx2.Client, or httpx2.AsyncClient for AsyncClient - is used
as it is, and never changed: credentials and headers go on each request. An
httpx.Client is refused, with the fix. Tracing comes from the HTTP client -
with OpenTelemetry (opentelemetry-instrumentation-httpx 0.65b0 or newer):
import httpx2
from opentelemetry.instrumentation.httpx import HTTPX2ClientInstrumentor
http = httpx2.Client()
HTTPX2ClientInstrumentor.instrument_client(http)
client = cent.Client(endpoint, api_key=key, http_client=http)
on_request is told of every request - method, commands and how many failed,
duration, status, error - for metrics without a dependency of cent's. It is a
plain function, also for AsyncClient, and must not raise.
Shutdown
client.close() - await client.aclose() - refuses new calls with
ClosedError and waits for the ones in progress, automatic batches included,
so that what was accepted is sent before the process exits. With timeout it
raises CentTimeoutError when calls are still in progress then. Both clients
are context managers which close themselves.
HTTP handlers
The proxy handlers and the endpoints client SDKs call have a framework-free
core - handler.handle(method, headers, body), await handler.ahandle(...) -
and serve as an ASGI app, handler.asgi, and a WSGI app, handler.wsgi. Their
functions may be blocking or async; under ASGI a blocking one runs in a thread.
Each function receives a cent.HTTPRequest: the method, headers, query and the
server's own request object in raw - the ASGI scope or the WSGI environ.
# FastAPI: a route calling the core
@app.post("/centrifugo/connect")
async def connect(request: Request) -> Response:
res = await connect_handler.ahandle(
request.method, request.headers, await request.body(), query=dict(request.query_params), raw=request
)
return Response(res.body, status_code=res.status, headers=dict(res.headers))
# Starlette, or any ASGI framework: mounted, the handler answers on the path
# with a trailing slash - point Centrifugo at .../centrifugo/connect/, or each
# call gets a 307 redirect first.
app.mount("/centrifugo/connect", connect_handler.asgi)
# Flask
from werkzeug.middleware.dispatcher import DispatcherMiddleware
app.wsgi_app = DispatcherMiddleware(app.wsgi_app, {"/centrifugo/connect": connect_handler.wsgi})
# Django, in urls.py
from django.views.decorators.csrf import csrf_exempt
def django_view(handler):
@csrf_exempt
def view(request):
res = handler.handle(request.method, request.headers, request.body, query=request.GET.dict(), raw=request)
return HttpResponse(res.body, status=res.status, headers=dict(res.headers))
return view
urlpatterns = [path("centrifugo/connect", django_view(connect_handler))]
Mounted as an ASGI or WSGI app, a handler runs outside your framework's
routing, so its function sees the request's headers but not, say, a FastAPI
dependency. To use your framework's authentication, call the core from a route
of your own, as the Django view does, and hand the function what it needs in
raw:
@app.post("/centrifugo/connect")
async def connect(request: Request, user: User = Depends(current_user)) -> Response:
res = await connect_handler.ahandle(request.method, request.headers, await request.body(), raw=user)
return Response(res.body, status_code=res.status, headers=dict(res.headers))
Proxy
cent.proxy is the backend side of Centrifugo's HTTP proxy, which calls your
application when a client connects, subscribes, publishes or makes an RPC
call: a handler per proxy type, taking a function.
from cent import proxy
def subscribe(request: cent.HTTPRequest, req: proxy.SubscribeRequest) -> proxy.SubscribeResult:
if not can_read(req.user, req.channel):
raise proxy.ProxyError(403, "permission denied")
return proxy.SubscribeResult()
subscribe_handler = proxy.SubscribeHandler(subscribe, on_error=log_proxy_error)
Return a result to accept the request, raise proxy.ProxyError to reject it
with an error the client receives, or proxy.Disconnect to close the client's
connection; any other exception fails the request, and goes to on_error to
be logged - on_error itself must not raise. So does a function returning
anything but its result - None, say: Centrifugo would take a response with
none of result, error and disconnect as accepting a subscribe, publish, RPC,
map publish or map remove as sent, as refusing a connect unless anonymous
connections are allowed, and as a refresh or sub refresh which expired. Error codes are in [400, 1999],
disconnect codes in [4000, 4999], and a disconnect reason is at most 32 bytes.
The values of a request's fixed-set fields have constants in cent.proxy:
req.encoding == proxy.ENCODING_BINARY, proxy.ALLOW_SUB, proxy.CAPABILITY_MATCH_WILDCARD,
proxy.CHANNEL_EVENT_TYPE_OCCUPIED, proxy.FILTER_NODE_OP_AND - the names the API's
constants have for the same field. Keep proxy endpoints reachable by Centrifugo only: whoever can call
them can claim to be any user. Put them on a network only Centrifugo reaches,
or check a secret header Centrifugo adds to every proxy request with the
proxy's static_headers option before the handler, and use TLS where the
traffic leaves a trusted network.
Tokens
cent.token issues the JWTs Centrifugo authenticates clients with -
connection and subscription tokens, with Centrifugo's claims, signed with
HMAC, RSA (2048 bits or more), ECDSA or Ed25519 - and cent.endpoints serves the endpoints the
getToken callbacks of client SDKs call:
from datetime import UTC, datetime, timedelta
from cent import endpoints, token
key = token.Key.hmac(secret) # client.token.hmac_secret_key
def issue(request: cent.HTTPRequest) -> str:
user = session_user(request)
if user is None:
raise endpoints.Forbidden # 403: the client SDK's UnauthorizedError; it stops asking
return token.connection(key, token.ConnectionClaims(user=user, expires_at=datetime.now(UTC) + timedelta(hours=1)))
connection_token = endpoints.ConnectionToken(issue, on_error=log_error)
endpoints.Forbidden answers 403, which client SDKs report as their
UnauthorizedError, stopping their requests. It is not cent.UnauthorizedError,
Centrifugo refusing this server's API credentials.
An expiry is required: an aware datetime, or token.NEVER for a token
accepted forever. endpoints.SubscriptionToken serves subscription tokens the
same way, with the channel the client asks for. To rotate keys without
restarting Centrifugo, see Key rotation with JWKS.
Key rotation with JWKS
By default Centrifugo verifies tokens with a single key from its
configuration: client.token.hmac_secret_key, or an RSA, ECDSA or Ed25519
public key. Changing that key means restarting Centrifugo, and from that
moment it refuses every token signed with the old key. To rotate keys without
that, your application can serve the keys itself, as a JSON Web Key Set (JWKS)
at Centrifugo's client.token.jwks_public_endpoint. Each key in the set has an
ID, and Centrifugo verifies a token with the key its kid header names:
from pathlib import Path
from cent import endpoints, token
# An ID for each key, never reused for another key: Centrifugo caches keys by ID.
key = token.Key.from_pem(Path("keys/2026-10.pem").read_bytes()).with_key_id("2026-10")
jwks = endpoints.JWKS(key) # served at the URL of jwks_public_endpoint
tok = token.connection(key, token.ConnectionClaims(user="42", expires_at=expires_at))
{"client": {"token": {"jwks_public_endpoint": "https://app.example.com/centrifugo/jwks"}}}
Only RSA, ECDSA and Ed25519 keys can go in a set (pip install cent[crypto]).
An HMAC secret has no public part to publish. Once jwks_public_endpoint is
set, Centrifugo verifies tokens with the set only, and refuses tokens signed
with the key it was configured with before. So moving to a JWKS is a
one-time restart.
How Centrifugo reads the set:
- when a token names a key ID Centrifugo doesn't know, it fetches the set again, at most once every 5 seconds;
- it keeps the keys it fetched for 5 minutes (an hour before Centrifugo v6.10.2), so a key dropped from the set stops working within that time;
- when the endpoint can't be reached, it keeps using the keys it already has;
- a token whose key isn't in the set is refused as expired, and the client SDK asks for a new token.
Rotate a key in three steps. Each step is one deploy of your application, and every instance should finish a step before any instance moves to the next:
- Publish the new key alongside the current one, and keep signing with
the current one:
endpoints.JWKS(current, new). - Sign with the new key. Centrifugo fetches the set the first time it sees the new ID.
- Drop the old key once every token it signed has expired: wait longer
than the longest
expires_atyou give.
If a key leaks, do all three steps now, without waiting in step 3. Within 5 minutes Centrifugo refuses new connections with the leaked key's tokens. Clients that connected before stay connected until their tokens expire: disconnect them with the server API if needed.
Centrifugo PRO's API tokens rotate the same way, from a set of their own at
http_api.jwks.endpoint (see Authentication).
token.APITokenSource(current_key=...) takes the key to sign with from a
function, so it can switch to the new key at step 2. Each API token is reused
for half its ttl, so in step 3 wait at least ttl after the switch.
Shared poll signatures
Clients tracking keys of a shared poll
channel need a signature from the backend. cent.sharedpoll.sign makes one,
and endpoints.SharedPollSignature serves the endpoint a subscription's
getSignature callback calls:
from cent import sharedpoll
def sign(request: cent.HTTPRequest, channel: str, keys: list[str]) -> tuple[list[str], str]:
allowed = readable(user, channel, keys) # the rest are revoked
return allowed, sharedpoll.sign(
secret, user=user, channel=channel, keys=allowed, expires_at=datetime.now(UTC) + timedelta(hours=1)
)
signature = endpoints.SharedPollSignature(sign)
Shared poll subscriptions are experimental in Centrifugo, and the module follows their changes.
Commands for async consumers
cent.command.publish(...) - and a method like it for every API method -
checks a request as a client would and encodes it,
for Centrifugo's async consumers:
its method and payload for an outbox table, or to_json() for a Kafka
message.
cmd = cent.command.publish(channel="news", data={"text": "hi"})
cur.execute("INSERT INTO centrifugo_outbox (method, payload, partition) VALUES (%s, %s, 0)", (cmd.method, cmd.payload))
payload is the request's JSON text: write it as it is, to the outbox's
jsonb column as above. Where the method goes apart from the payload - the
outbox's method column, a message header or attribute - Centrifugo reads the
payload as the request itself, so a JSON string holding it -
json.dumps(cmd.payload) - is a bad request there, dropped with only
Centrifugo's log saying so. Only a message which is a whole command,
to_json()'s, may hold its payload as a string, for CDC pipelines.
A consumer keeps commands in order only within a partition: to keep a channel's commands in order, derive their partition from the channel the same way in every writer.
Streaming AI output
Publish a model's output into a channel of its own, in a namespace with history and recovery, from one task - each publish waiting for the previous one - in chunks of what arrived every 50 ms or so, not a publication per token. See Centrifugo for AI apps, which also covers sizing history for a whole response.
Testing
Test code which uses cent without Centrifugo: give the client an http_client
whose transport answers as Centrifugo does - each method at /api/<method>,
its reply {"result": {...}} or {"error": {"code": ..., "message": ...}}:
REPLIES = {
"/api/publish": {"result": {"offset": 1, "epoch": "e"}},
# One response per channel, in order.
"/api/broadcast": {
"result": {"responses": [{"result": {"offset": 1}}, {"error": {"code": 102, "message": "unknown channel"}}]}
},
# One reply per command, in order.
"/api/batch": {"replies": [{"publish": {"offset": 1}}, {"error": {"code": 102, "message": "unknown channel"}}]},
}
def centrifugo(request: httpx2.Request) -> httpx2.Response:
return httpx2.Response(200, json=REPLIES[request.url.path])
client = cent.Client("http://centrifugo/api", http_client=httpx2.Client(transport=httpx2.MockTransport(centrifugo)))
cent.AsyncClient takes an httpx2.AsyncClient with the same transport. A
test double of your own returns cent's results and raises its errors, partial
failures included:
ok = cent.ChannelResult(channel="news", result=cent.PublishResult(offset=1))
bad = cent.ChannelResult(channel="unknown:x", error=cent.ApiError.from_wire(102, "unknown channel"))
raise cent.BroadcastFailedChannelsError([bad], 2, cent.BroadcastResult(channels=[ok, bad], replied=True))
and for a batch, cent.Pending.resolved(result) or
cent.Pending.resolved(error=...) as each command's outcome, with
cent.BatchFailedCommandsError(failed, total, cent.BatchResult(True, failed))
of cent.FailedCommand(index, method, error).
More
- API.md: the API reference, every class, function and field, made
from the docstrings by
make docs. - Docs for agents and LLMs: centrifugal.dev/llms.txt, an index of the current (v6) documentation.
- Development: see AGENTS.md;
make checkruns what CI does but the integration tests,make test-integrationthose.
MIT license. Centrifugo PRO, which the methods marked "Centrifugo PRO only" call, is commercial software under its own license.
Metadata
Release files for cent 6.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| cent-6.0.0.tar.gz | 223.2 kB | Without provenance | Details for cent-6.0.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| cent-6.0.0-py3-none-any.whl | Python 3 | none | any | Details for cent-6.0.0-py3-none-any.whl |
Total release size: 359.6 kB
Release files / cent-6.0.0.tar.gz
| Download URL | cent-6.0.0.tar.gz |
|---|---|
| Size | 223.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
cac00a5f07cf329afcdf4d8622adc22720eacdea9bc7ff26c285e73f142b502b
|
|
BLAKE2b-256 checksum How to use checksums |
61989b12f47d420dcfa16cd1071196e10920aba0d4089f04ab269125030510be
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Release files / cent-6.0.0-py3-none-any.whl
| Download URL | cent-6.0.0-py3-none-any.whl |
|---|---|
| Size | 136.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
45a9c9ca0834dd7b8fe2d0654518dcb64722e9e17eab59ba3b7a48c9e3239110
|
|
BLAKE2b-256 checksum How to use checksums |
b5fdd8d2442cb2b4935035b1a9795c90caa80d908fafca9815915ca1ca8e7533
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Security for cent 6.0.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.