Application¶
The application object and its configuration.
Veloce
¶
Bases: AsgiMixin, DispatchMixin, ErrorsMixin, IntrospectionMixin, LifecycleMixin, MCPMixin, MiddlewareMixin, MountingMixin, OpenAPIMixin, PluginsMixin, ServingMixin, TestingMixin, BackgroundTasksMixin, TemplatingMixin, Router
Ultra-fast async web framework.
Usage::
app = Veloce()
@app.get("/")
async def index(request: Request):
return {"message": "Hello, World!"}
app.run()
jinja_env
property
¶
The app's shared Jinja2 Environment, mutable in place.
Available once a template_folder has been configured; raises
RuntimeError when no templating is.
jinja_loader
property
¶
The app's Jinja template loader, or None when no templating is set up.
middlewares
property
¶
middlewares: tuple[Middleware, ...]
The registered Middleware instances, in the order they will run.
Registration order unless priorities were set, in which case this is the priority order the pipeline uses. Standard ASGI middleware classes are not here; they wrap the app when the ASGI stack is assembled.
Usage::
if not any(isinstance(m, CORSMiddleware) for m in app.middlewares):
app.add_middleware(CORSMiddleware, allow_origins=["*"])
view_functions
property
¶
A {endpoint_name: handler} view of registered routes.
Named by the route's name= kwarg or the handler's __name__, prefixed
with <bpname>. for a blueprint route. A fresh snapshot per call, so
mutation does not poison framework state.
error_handler_spec
property
¶
Inspection view of registered error handlers.
A {blueprint_name_or_None: {key: handler}} mapping, keyed by integer
status code or exception class. Blueprint handlers are scoped to their
own routes at dispatch time, so they appear under their blueprint name
here, not folded into None.
before_request_funcs
property
¶
View of registered before_request hooks.
{blueprint_name_or_None: [hook, ...]}. The dispatcher walks the None
bucket plus the one matching the matched route's endpoint prefix.
after_request_funcs
property
¶
Return the per-blueprint after-request hook registry.
teardown_request_funcs
property
¶
Return the per-blueprint teardown-request hook registry.
blueprints
property
¶
Snapshot mapping of bp.name -> Blueprint.
A fresh copy; re-registering a name overwrites the previous entry.
url_value_preprocessors
property
¶
View of registered URL-value preprocessors.
{blueprint_name_or_None: [fn, ...]}, each blueprint under its dotted
name. A nested blueprint's entry is the flattened chain that runs for
its routes, outermost first.
url_default_functions
property
¶
View of registered URL-default callbacks, keyed as url_value_preprocessors.
debug
property
writable
¶
Whether debug mode is enabled; bound to config['DEBUG'].
A dotenv-style string (DEBUG=false) is interpreted rather than treated
as truthy because it is non-empty.
secret_key
property
writable
¶
Session-signing secret; bound to config['SECRET_KEY'].
SessionMiddleware constructed without an explicit secret_key=
resolves it from here on the first request, so app.secret_key = ...
and config['SECRET_KEY'] are one and the same setting.
url_map
property
¶
url_map: URLMap
Read-only mapping of registered URL rules.
Iterating yields URLRule objects (rule, methods, endpoint),
subscripting by endpoint name returns that endpoint's rules, and len()
is the total route count.
instrumentation_hooks
property
¶
The registered instrumentation hooks, in the order they will run.
The read half of add_instrumentation. A tuple, so a caller cannot
register or reorder through it.
json
property
writable
¶
Active JSONProvider instance.
Lazily instantiated from app.json_provider_class, so swapping encoders
is app.json_provider_class = MyJSONProvider; app.json = instance
replaces it explicitly.
The provider serialises every value a handler returns, and an app that configures nothing keeps the direct backend path. It does not reach the framework's own wire formats: cache keys always sort so equal mappings hash alike, and signed cookies, JWTs and protocol frames are not the application's to restyle.
package_root
property
¶
Filesystem path of the directory containing import_name's module.
Named package_root rather than root_path because Veloce.root_path
already means the ASGI mount prefix - one is a location on disk, the
other a URL prefix.
instance_path
property
¶
Writable instance folder beside the package.
<package_root>/instance, for config, SQLite files and uploads, unless
an explicit instance_path= overrides it. Not auto-created.
signal_namespace
property
¶
Accessor that returns the veloce.signals module.
The signals are module-level singletons, so
app.signal_namespace.request_started is veloce.signals.request_started.
aborter
property
writable
¶
Callable that raises typed HTTPExceptions by status code.
app.aborter(404) is the module-level abort(404). A distinct attribute
so an application can subclass Aborter for custom code-to-exception
mappings, by assignment or by mutating the instance this returns. One per
application, so a mutation sticks and reaches no other app.
got_first_request
property
¶
True after the first request has been fully handled.
Read-only, for conditional setup that depends on whether the app has bootstrapped yet.
cli
property
¶
Click Group for app-defined custom CLI commands.
Lazily constructs a click.Group once. Custom commands attach via the
standard Click decorator:
@app.cli.command("init-db")
def init_db():
...
The veloce console script mounts the group as a custom subcommand
when launched with an app reference. click is required at access time
but not at import time.
dependency_overrides
property
writable
¶
Mutable map of dependency callables to test replacements.
Populate it to swap a real dependency for a fake one in tests::
app.dependency_overrides[get_db] = get_fake_db
The resolver consults it on every request, so a change takes effect
immediately, and .clear() removes every override.
route
¶
route(path: Annotated[str, Doc('URL path template, including `{param}` / `{param:converter}` placeholders.')], methods: Annotated[list[str] | None, Doc('HTTP methods this handler serves; defaults to `GET`.')] = None, dependencies: Annotated[list[Any] | None, Doc('Dependencies run for this route, appended after the router-level ones.')] = None, response_model: Annotated[Any, _DOC_RESPONSE_MODEL] = _INFER_RESPONSE_MODEL, tags: Annotated[list[str] | None, Doc('OpenAPI tags for this route, combined with the router-level tags.')] = None, summary: Annotated[str | None, Doc('Short OpenAPI summary for this operation.')] = None, name: Annotated[str | None, Doc("Endpoint name for `url_for` reverse lookup; defaults to the handler's name.")] = None, description: Annotated[str | None, Doc("OpenAPI description; defaults to the handler's docstring.")] = None, deprecated: Annotated[bool, Doc('Mark the operation as deprecated in the OpenAPI document.')] = False, response_description: Annotated[str, Doc('Description of the successful response in the OpenAPI document.')] = MSG_SUCCESSFUL_RESPONSE, status_code: Annotated[int, Doc('Default HTTP status code for a successful response.')] = HTTP_200_OK, response_class: Annotated[Any, Doc('Response class for this route, overriding the router and framework defaults.')] = None, response_model_include: Annotated[set[str] | None, Doc('Fields to include when serializing the response model.')] = None, response_model_exclude: Annotated[set[str] | None, Doc('Fields to exclude when serializing the response model.')] = None, response_model_exclude_unset: Annotated[bool, Doc('Omit fields left unset on the response model from the serialized output.')] = False, response_model_exclude_defaults: Annotated[bool, Doc('Omit fields equal to their default on the response model from the serialized output.')] = False, response_model_by_alias: Annotated[bool, Doc('Serialize the response model using field aliases instead of attribute names.')] = False, response_model_exclude_none: Annotated[bool, Doc('Omit fields whose value is `None` from the serialized response model.')] = False, include_in_schema: Annotated[bool, Doc('Register the route but omit it from the generated OpenAPI document when False.')] = True, responses: Annotated[dict[int, dict[str, Any]] | None, Doc('Additional OpenAPI responses for this route, overlaid on the router-level ones.')] = None, operation_id: Annotated[str | None, Doc('Explicit OpenAPI `operationId`; defaults to the route name.')] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc("Arbitrary dict deep-merged into this route's OpenAPI operation object.")] = None, defaults: Annotated[dict[str, Any] | None, Doc('Fixed values merged into the path params at dispatch without overriding URL-matched ones.')] = None, callbacks: Annotated[dict[str, Any] | None, Doc("OpenAPI Callback objects emitted verbatim into the operation's `callbacks` field.")] = None, strict_slashes: Annotated[bool | None, Doc('When False, match both slashed and unslashed forms; `None` defers to the app policy.')] = None, subdomain: Annotated[str | None, Doc('Constrain the route to a subdomain of `SERVER_NAME`; `*` matches any non-apex subdomain.')] = None, host: Annotated[str | None, Doc('Constrain the route to an exact `Host` header value (case-insensitive).')] = None, expose_as_mcp_tool: Annotated[bool, Doc('Expose the route as an MCP tool in the contrib MCP registry.')] = False, mcp_description: Annotated[str | None, Doc("LLM-facing description for the route's MCP tool, required when exposed as one.")] = None, expose_as_mcp_resource: Annotated[bool, Doc('Expose the read-only route as an MCP resource in the contrib MCP registry.')] = False, mcp_resource_uri: Annotated[str | None, _DOC_MCP_RESOURCE_URI] = None, mcp_resource_mime_type: Annotated[str | None, _DOC_MCP_RESOURCE_MIME_TYPE] = None, mcp_meta: Annotated[dict[str, Any] | None, _DOC_MCP_META] = None, mcp_resource_size: Annotated[int | None, Doc("Size in bytes advertised for the route's MCP resource.")] = None, mcp_resource_annotations: Annotated[dict[str, Any] | None, Doc("Annotations (audience, priority) advertised for the route's MCP resource.")] = None, mcp_scopes: Annotated[Sequence[str] | None, Doc('Authorization scopes required to call this route over MCP.')] = None, mcp_icons: Annotated[Sequence[Any] | None, Doc('Optional MCP `Icon` objects a client may render next to the tool/resource.')] = None, mcp_task_support: Annotated[bool, _DOC_MCP_TASK_SUPPORT] = False, exclude_middleware: Annotated[Sequence[str | type[Any]] | None, _DOC_EXCLUDE_MIDDLEWARE] = None, stream: Annotated[bool, _DOC_STREAM] = False) -> Callable[[T_route], T_route]
Register a route for any set of HTTP methods.
exclude_middleware=["CSRFMiddleware"] opts this route out of the
named middleware (matched against each middleware's name), so a
webhook or health-check route can skip CSRF, auth, or rate limiting
without forking the middleware. Routes that declare no exclusions
pay no extra per-request cost.
get
¶
GET route decorator. Safe and idempotent - RFC 9110 Sec. 9.3.1.
post
¶
POST route decorator - RFC 9110 Sec. 9.3.3.
put
¶
PUT route decorator. Idempotent - RFC 9110 Sec. 9.3.4.
patch
¶
PATCH route decorator - RFC 5789.
delete
¶
DELETE route decorator. Idempotent - RFC 9110 Sec. 9.3.5.
head
¶
HEAD route decorator. Like GET with no body - RFC 9110 Sec. 9.3.2.
options
¶
OPTIONS route decorator - RFC 9110 Sec. 9.3.7.
trace
¶
TRACE route decorator - RFC 9110 Sec. 9.3.8.
query
¶
QUERY route decorator - RFC 10008.
QUERY is safe and idempotent like GET but carries a request body like
POST, for read-only operations whose parameters do not fit a URL (search,
filtering, paging). The handler reads the body exactly as a POST handler
does (request.get_json() / a body model parameter).
websocket
¶
websocket(path: Annotated[str, Doc('URL path template for the WebSocket route, including `{param}` placeholders.')]) -> Callable[[RouteHandler], RouteHandler]
Register a WebSocket route via decorator.
websocket_listener
¶
websocket_listener(path: str, *, receive: str = 'json', send: str = 'json', on_connect: RouteHandler | Callable[..., Any] | None = None, on_disconnect: RouteHandler | Callable[..., Any] | None = None) -> Callable[[RouteHandler | Callable[..., Any]], RouteHandler | Callable[..., Any]]
Register a WebSocket route wrapping a per-message callback.
The decorated callback handles one message at a time; the framework
owns the accept handshake, the receive loop, and the clean close on
disconnect. The callback is called as cb(data), or cb(ws, data)
when its first parameter is named ws/socket (or it takes two
positional parameters). Returning a non-None value sends it back in
send mode; returning None sends nothing.
receive/send select the codec ("json" default, or "text" /
"bytes"). on_connect(ws) runs after accept; on_disconnect(ws)
always runs when the loop ends, including on peer disconnect. Sync
callbacks and hooks are offloaded to the executor.
Usage::
@app.websocket_listener("/echo")
async def echo(data):
return data
For full control over the handshake and loop use @app.websocket.
add_websocket_route
¶
add_websocket_route(path: Annotated[str, Doc('URL path template for the WebSocket route, including `{param}` placeholders.')], handler: Annotated[RouteHandler, Doc('Callable invoked with the accepted WebSocket connection when the route matches.')]) -> None
Register a WebSocket route imperatively (ASGI shape).
The non-decorator form of @app.websocket(path).
add_api_websocket_route
¶
Register an imperative WebSocket route, mirroring add_api_route.
The non-decorator form of @app.websocket(path). name, when given,
registers the route for reverse lookup so app.url_for(name) resolves
to its path.
add_api_route
¶
add_api_route(path: str, endpoint: RouteHandler, *, methods: list[str] | None = None, **kwargs: Any) -> None
Register a route imperatively.
The non-decorator form: the handler argument is named endpoint
here and forwarded to add_route (where it is handler). All
route kwargs - response_model, tags, dependencies,
status_code, openapi_extra, ... - pass straight through.
Defaults to ["GET"] when methods is omitted.
url_for
¶
Build the URL for name, applying the @app.url_defaults callbacks.
They run before delegating to Router.url_for, so injected defaults
appear in the rendered URL. On build failure each registered
app.url_build_error_handlers callback is invoked with
(error, endpoint, values) in order and the first non-None return is
used; BuildError is raised if none recovers.
url_path_for
¶
Resolve a URL path by endpoint name and parameters.
iter_routes
¶
iter_routes(*, include_hidden: bool = False) -> list[tuple[str, str, RouteInfo]]
Return every registered route as (method, path, info).
app.routes is a summary view: six fields of RouteInfo's full
record, which is enough to render a route table and not enough for
anything that inspects a route. This returns the records themselves, so
response models, dependencies, security requirements and the rest are
reachable without touching private state.
Hidden routes - WebSocket routes and those registered
include_in_schema=False - are omitted unless include_hidden is
set; the default is the schema-visible set.
Usage::
for method, path, info in app.iter_routes():
if info.response_model is not None:
print(method, path, info.response_model)
handle_request
async
¶
Handle one request - run the middleware chain, then route dispatch.
cp is the compiled pipeline, threaded in by __call__ so the
generation check runs once per request; a direct caller passes None.
log_exception
¶
log_exception(exc: BaseException, request: Request | None = None) -> None
Log an exception with traceback.
Routes the exception through the app's own logger at ERROR level, so an
operator silences it with ordinary logging configuration. Pass request
to name the request that failed; a background task or CLI hook omits it.
make_default_options_response
¶
make_default_options_response(path: str, allowed_methods: list[str] | None = None) -> Response
Build the auto-OPTIONS response for path.
Returns a 200 response with an empty body and an Allow header listing
every method registered for path, augmented with HEAD (whenever
GET is supported) and OPTIONS itself per RFC 9110 Sec. 9.3.7. Pass
allowed_methods when the registered set is already known.
lifespan_context
¶
Return an async context manager driving the lifespan cycle.
async with app.lifespan_context(): ... runs the full startup sequence
on entry and the shutdown sequence on exit, independent of any request -
for tests, and for embedding the app without an ASGI server.
spawn
¶
spawn(coro: Annotated[Coroutine[Any, Any, Any], Doc('Coroutine to run as a background task.')], *, name: Annotated[str | None, Doc('Name the task is registered under; anonymous when omitted.')] = None) -> Task[Any]
Schedule a long-lived, app-scoped background task.
A spawned task lives for the application's lifetime: it is tracked with
a strong reference, so the loop cannot GC it mid-flight, and is
cancelled-and-drained at shutdown within the GRACEFUL_TASK_TIMEOUT
budget. Pass name to make it retrievable and cancellable by name; a
duplicate name raises. Requires a running event loop.
Usage::
@app.on_startup
async def _start_poller():
app.spawn(poll_queue(), name="queue-poller")
context_processor
¶
Register a context processor returning a dict to merge into the context.
template_filter
¶
Register a function as a Jinja filter.
Usage::
@app.template_filter("upper")
def upper(s): return s.upper()
name defaults to the function's own __name__.
template_global
¶
Register a callable as a Jinja global, reachable by name in a template.
Same shape as template_filter.
add_template_global
¶
Imperative equivalent of @template_global.
template_test
¶
Register a Jinja test - used in {% if x is name %} constructs.
add_template_filter
¶
Imperative equivalent of @template_filter.
add_template_test
¶
Imperative equivalent of @template_test.
update_template_context
¶
Merge registered context-processor output into context.
Folds the returned dicts in in place without overriding keys the caller already set - explicit context wins - and returns the same dict.
get_spawned_task
¶
Return the named spawned task, or None if there is no such task.
cancel_spawned_task
¶
Cancel a named spawned task. Return whether a task was cancelled.
supervise
¶
supervise(coro_factory: Annotated[Callable[[], Coroutine[Any, Any, Any]], Doc('Zero-argument callable returning a fresh coroutine on every restart.')], *, name: Annotated[str, Doc('Name the supervised task is registered under.')], max_restarts: Annotated[int, Doc('Restarts allowed inside `restart_window` before giving up.')] = 5, restart_window: Annotated[float, Doc('Seconds the restart budget is counted over.')] = 60.0, backoff: Annotated[float, Doc('Seconds to wait before the first restart.')] = 1.0, max_backoff: Annotated[float, Doc('Ceiling the doubling backoff is clamped to.')] = 30.0) -> Task[Any]
Run a long-lived coroutine, restarting it on failure.
coro_factory returns a fresh coroutine on each call - the supervisor
calls it to start and again to restart, so a single coroutine object is
not accepted. A normal return is restarted too, a raise is logged and
restarted after a bounded backoff, and asyncio.CancelledError is never
suppressed.
A count-within-window breaker bounds runaway restarts: at most
max_restarts within any restart_window seconds, with the counter and
the doubling backoff reset by any run longer than the window. The
supervisor itself runs as an app.spawn(...) task, so name is
required and a duplicate raises.
Usage::
@app.on_startup
async def _start():
app.supervise(lambda: poll_queue(), name="queue-poller")
wait_for_background_tasks
async
¶
Wait for every currently-spawned background task to finish.
True when they all completed, False when timeout elapsed first.
Tasks are left running either way - this waits, it does not cancel.
Newly spawned tasks are picked up too, so a task that spawns another is
waited for in full.
Usage::
await app.wait_for_background_tasks()
test_client
¶
test_client(**kwargs: Any) -> TestClient
Return an in-memory TestClient for this app.
Kwargs are forwarded to TestClient.__init__.
async_test_client
¶
async_test_client(**kwargs: Any) -> AsyncTestClient
Return an AsyncTestClient for this app.
Requests are awaited on the test's own running loop rather than driven
through a private one. Kwargs are forwarded to AsyncTestClient.__init__.
app_context
¶
Bind current_app and reset g for use outside a request.
Nestable: the previous binding, if any, is restored on exit.
test_request_context
¶
test_request_context(path: str = '/', method: str = HTTP_METHOD_GET, headers: dict[str, str] | None = None, query_string: str = '', body: bytes = b'') -> _TestRequestContext
Synthesise a fake request for outside-request testing.
A strict subset of what handle_request does: no middleware, no DI,
no handler.
run
¶
run(host: Annotated[str | None, Doc('Interface to bind; defaults to `127.0.0.1`. Conflicts with `bind_all`.')] = None, port: Annotated[int, Doc('TCP port to listen on.')] = 8000, workers: Annotated[int, Doc('Must be `1`; the built-in server runs a single process.')] = 1, access_log: Annotated[bool, Doc('Print the start-up banner and install the development access log.')] = True, ssl_context: Annotated[SSLContext | None, Doc('Serve HTTPS for local testing when given.')] = None, bind_all: Annotated[bool, Doc('Bind every interface (`0.0.0.0`) instead of localhost.')] = False, reload: Annotated[bool, Doc('Restart the server whenever a project `.py` file changes.')] = False) -> None
Start the built-in development server.
This from-scratch HTTP server is for local development only; in
production run the app under a hardened ASGI server
(uvicorn your_module:app), which its ASGI __call__ supports.
host resolves to "127.0.0.1" when unset, and is mutually
exclusive with bind_all=True - passing both raises ValueError
rather than silently widening privilege. 0.0.0.0 exposes the dev
server to every reachable network, so use it only in a trusted
environment and never with debug=True.
ssl_context is handed straight to loop.create_server(ssl=...);
left None, the serving path is byte-for-byte the plain-HTTP one.
workers must be 1 - the built-in server does not pre-fork, so
anything else raises ValueError.
reload=True makes this process supervise a serving child and restart
it on any project .py change; the watching stays in the supervisor,
so the child carries no overhead.
install
¶
Install plugin and return it.
A named plugin is recorded under self.extensions[name] only after its
install returns, so a failed install leaves no partial registry entry.
openapi
¶
Return the generated OpenAPI schema dict.
Cached in app.openapi_schema; mutating the returned dict in place
changes what the UI and JSON endpoints serve. Assign that attribute
before any request lands to bypass the auto-build entirely.
mount
¶
mount(prefix: Annotated[str, Doc('Full path the sub-application is served at.')], app: Annotated[Any, Doc('A `Veloce` sub-app, an ASGI application, or a `StaticFiles`.')], *, expose_mcp: Annotated[bool, Doc("Also publish the sub-app's MCP tools through this app's server.")] = False) -> None
Mount a sub-application at a path prefix.
prefix is the full path the sub-app is reached at; this app's own
Veloce(prefix=...) does not apply here, since a mount places an application
rather than registering a route.
A Veloce sub-app is dispatched through the parent's request pipeline, and
the parent drives its startup and shutdown. Any other ASGI app is
dispatched at the ASGI layer with the prefix moved from path to
root_path, receives http and websocket scopes only - never
lifespan - and owns its entire prefix subtree.
Registering a prefix equal to, nested under, or containing an existing
mount raises ValueError.
expose_mcp=True also publishes the sub-app's MCP tools, resources and
prompts through the parent's server, prefixed by the mount.
mount_static
¶
mount_static(prefix: Annotated[str, Doc('URL path the directory is served under.')] = '/static', directory: Annotated[str, Doc('Directory to serve, absolute or relative to the package root.')] = 'static', html: Annotated[bool, Doc('Serve `index.html` for a directory request, in HTML mode.')] = False, must_exist: Annotated[bool, Doc('Refuse a missing directory; `False` downgrades it to a warning.')] = True) -> None
Mount a static file directory.
The directory must exist and be readable at wiring time (a typo
otherwise 404s every asset silently); pass must_exist=False to
downgrade the check to a warning when the directory is created after
the app is constructed.
add_middleware
¶
add_middleware(middleware: Annotated[Any, Doc('A `Middleware` instance, a middleware class, or an ASGI wrapper class.')], **options: Annotated[Any, Doc('Keyword arguments the middleware class is built with.')]) -> None
Add middleware to the pipeline.
Call forms:
add_middleware(VeloceMiddlewareClass, **options)- a class subclassingMiddlewareis instantiated with**optionsand appended to the request/response pipeline.add_middleware(instance)- append an already-builtMiddlewareinstance directly.add_middleware(ASGIMiddlewareClass, **options)- a class that is not aMiddlewaresubclass is treated as standard ASGI middleware, instantiated asASGIMiddlewareClass(app, **options)when the stack is assembled. Middleware added first is the outermost wrapper.
Pass name= to override the instance's exclusion name (the identifier
exclude_middleware=[...] on a route references). It is applied after
construction, so per-instance naming works even for a subclass whose
__init__ does not accept a name keyword.
Pass priority= (an int, default 0) to order this middleware
regardless of registration order. Higher priority runs earlier in the
request phase and later in the response phase, with equal priorities
keeping registration order. It applies to the request/response pipeline
only, not to ASGI-class middleware, which its wrap nesting orders.
add_http_middleware
¶
Register a middleware on the (request, call_next) -> response chain.
Accepts a BaseHTTPMiddleware instance, a bare callable, or a class
(which is instantiated with no args). Returns the registered object so
it can be used as a decorator.
middleware
¶
middleware(middleware_class_or_type: type[Any] | str, **kwargs: Any) -> Callable[[Callable[..., Any]], Callable[..., Any]] | None
Add middleware - supports both a class form and a decorator form.
The decorator form returns the decorator; the class form returns
None, so @app.middleware(CORSMiddleware) fails at decoration
rather than silently doing nothing.
Class form: app.middleware(CORSMiddleware, allow_origins=["*"]) Decorator form: @app.middleware("http") async def add_header(request, call_next): response = await call_next(request) response.headers["X-Custom"] = "value" return response
mcp_tool
¶
mcp_tool(description: Annotated[str, Doc('Required LLM-facing description, separate from the docstring.')], *, name: Annotated[str | None, Doc("Tool name; defaults to the decorated function's own.")] = None, namespace: Annotated[str | None, Doc('Prefix qualifying the tool name, for a shared catalogue.')] = None, scopes: Annotated[Sequence[str] | None, Doc('Scopes the calling principal must hold to see and call it.')] = None, tags: Annotated[Sequence[str] | None, Doc('Free-form labels published with the tool.')] = None, icons: Annotated[Sequence[Icon] | None, Doc('Icons a client may render beside the tool.')] = None, task_support: Annotated[bool, Doc('Allow the call to be started as a long-running MCP task.')] = False, annotations: Annotated[dict[str, Any] | None, Doc('MCP tool annotations, such as `readOnlyHint`.')] = None, meta: Annotated[dict[str, Any] | None, Doc('Opaque `_meta` published with the tool.')] = None, version: Annotated[str | None, Doc('Version string published with the tool.')] = None) -> Callable[..., Any]
Register an MCP-only tool callable by an AI agent (contrib.mcp).
The decorated coroutine (or sync function) becomes an MCP tool whose
input JSON Schema is derived from its signature; Depends() params
resolve through the same dependency machinery routes use, with an
MCPContext standing in for the HTTP Request. description is the
required LLM-facing text (separate from the docstring). namespace
prefixes the tool name (<namespace>_<name>), mirroring how a
blueprint namespaces an exposed route. icons is an optional list of
Icon objects a client may render next to the tool. task_support=True
lets a client run the tool as a background task (task-augmented
tools/call, polled via tasks/get / tasks/result). version labels
this registration: two tools sharing a name and declaring different
versions are both registered, the higher one is listed, and a call
naming no version reaches it.
Usage::
@app.mcp_tool(description="Add two integers")
async def add(a: int, b: int) -> int:
return a + b
mcp_prompt
¶
mcp_prompt(description: str, *, name: str | None = None, namespace: str | None = None, scopes: Sequence[str] | None = None, icons: Sequence[Icon] | None = None, meta: dict[str, Any] | None = None) -> Callable[..., Any]
Register an MCP prompt template fetchable by an AI agent (contrib.mcp).
The decorated callable's parameters become the prompt's arguments, and its
return - a string, or a list of role/content messages - becomes the
messages prompts/get returns. Depends() params resolve through the
same dependency machinery routes use, with an MCPContext standing in for
the HTTP Request. description is the required LLM-facing text;
namespace prefixes the prompt name (<namespace>_<name>). icons is an
optional list of Icon objects a client may render next to the prompt.
Usage::
@app.mcp_prompt(description="Summarise a topic in three bullets")
async def summarise(topic: str) -> str:
return f"Summarise {topic} in three bullet points."
add_mcp_tool
¶
Register an already-built MCPTool (contrib.mcp).
The decorator builds a tool from a handler; this takes one that already
exists - most often from derive_tool, which narrows a registered tool
into the façade an agent should see::
app.add_mcp_tool(derive_tool(internal, name="search", arguments={...}))
before_mcp_call
¶
Register a hook that runs before every MCP call (contrib.mcp).
Called with the primitive's name and the arguments it was given. Return
None to let the call proceed, or any other value to answer with that
instead of invoking the handler - the same short-circuit shape
before_request has. Raising an MCPError reports the failure to the
client, which is how an authorization check refuses a call.
Unlike before_request, this reaches a tool registered with
@app.mcp_tool, which has no route and so no request lifecycle::
@app.before_mcp_call
async def audit(name, arguments):
log.info("mcp call", extra={"tool": name})
after_mcp_call
¶
Register a hook that runs after every MCP call (contrib.mcp).
Called with the primitive's name and the handler's return value, and returns the value to send on - so a hook may rewrite a result, or return it unchanged. Hooks run in registration order, each seeing what the last returned. It does not run when the call raised.
mcp_completer
¶
mcp_completer(*, argument: str, prompt: str | None = None, resource: str | None = None) -> Callable[..., Any]
Register an argument-value completer for an MCP prompt or resource (contrib.mcp).
The decorated callable suggests values for one argument of a prompt
(named) or a resource (by URI template) as the user types, answering the
MCP completion/complete request. It is called with the partial value
and a mapping of the sibling argument values already resolved, and returns
a sequence of candidate strings (or a CompletionResult for explicit
totals). Pass exactly one of prompt or resource. An argument with no
registered completer answers with an empty completion.
Usage::
@app.mcp_completer(prompt="greet", argument="name")
async def complete_name(value: str, context: dict[str, str]) -> list[str]:
return [n for n in KNOWN_NAMES if n.startswith(value)]
mount_mcp
¶
mount_mcp(transport: Annotated[str, Doc('One of `stdio`, `http`, or the deprecated `sse`.')] = 'stdio', *, path: Annotated[str, Doc('Where an HTTP or SSE transport mounts; ignored on stdio.')] = '/mcp', auth: Annotated[Any, Doc('An `MCPAuth` making an HTTP endpoint an OAuth 2.1 resource server.')] = None, principal: Annotated[Any, Doc('`Principal` whose identity and scopes the served tools run under.')] = None, allowed_origins: Annotated[Sequence[str] | None, Doc('Enable `Origin` validation, the DNS-rebinding defense.')] = None, exclude_middleware: Annotated[Sequence[str] | None, Doc('App middleware the transport routes opt out of.')] = None, sessions: Annotated[bool, Doc('Opt into the `Mcp-Session-Id` lifecycle.')] = False, resumable: Annotated[bool, Doc('Opt into SSE resumability, replaying missed events on reconnect.')] = False, tool_filter: Annotated[Any, Doc('`(tool, principal) -> bool` narrowing what `tools/list` reports.')] = None, cache_ttl_ms: Annotated[int | None, Doc('Freshness hint sent with cacheable results; `0` marks them stale.')] = None, page_size: Annotated[int | None, Doc('Opt the list methods into cursor pagination at this page size.')] = None, tool_search: Annotated[bool, Doc('Publish `search_tools` / `describe_tools` / `run_tools` in place of the catalogue.')] = False, session_backend: Annotated[Any, Doc('Store sharing HTTP sessions between workers, with async `read`/`write`/`delete`.')] = None, message_path: Annotated[str, Doc('URL an SSE stream names for the client to POST to; ignored elsewhere.')] = '/messages') -> Any
Build the MCP server and serve the registered tools.
Assembles the tool registry from @app.mcp_tool registrations plus every
route flagged expose_as_mcp_tool=True, the resource registry from every
read-only route flagged expose_as_mcp_resource=True, and the prompt
registry from @app.mcp_prompt registrations, then serves them over the
chosen transport. Call this after the tool / resource / prompt routes are
registered.
Transports
transport="stdio" (the default) serves JSON-RPC 2.0 on stdin/stdout for
subprocess use and returns an awaitable serve coroutine that runs until
stdin closes, inside the app's lifespan_context() - so every
on_startup handler runs before the first tool is served. Schedule it
explicitly (asyncio.run(app.mount_mcp())).
transport="http" mounts the Streamable HTTP transport as a POST route
at path (default /mcp) on this app and returns None; serve the app
with any ASGI server (or app.run()) as usual.
transport="sse" mounts the deprecated split-endpoint wire of MCP
revision 2024-11-05, for a client that speaks only that: a GET at path
(defaulting to /sse) opens a stream that names message_path as the URL
to POST to, each POST is acknowledged 202 and its JSON-RPC response
arrives on the stream. Prefer transport="http" for anything new - one
endpoint, and a dropped connection can be resumed.
Arguments, in signature order:
path is where an HTTP or SSE transport mounts; ignored on stdio.
auth (a veloce.contrib.mcp.MCPAuth) makes an HTTP endpoint an
OAuth 2.1 resource server - validating the bearer token on every request
and serving the RFC 9728 metadata.
principal (a veloce.Principal) establishes the identity and scopes the
served tools run under. A local subprocess is trusted, so this is how a
stdio server takes its identity from the environment.
allowed_origins enables Origin validation - the DNS-rebinding defense.
exclude_middleware names app middleware the transport routes opt out of
(an app-wide auth middleware that auth replaces, for instance).
sessions opts into the Mcp-Session-Id lifecycle: the server assigns a
session id on initialize, requires it on later requests (400 missing,
404 once terminated), and accepts a DELETE to terminate it.
resumable opts into SSE resumability: each streamed event gets an id
encoding its stream, and a GET carrying Last-Event-ID replays only
that stream's missed events, so a client can reconnect after a dropped
connection.
tool_filter narrows what tools/list reports per caller beyond the
declared scopes: a callable (tool, principal) -> bool (sync or async)
that hides tools an agent has no business seeing, so its context is not
spent on tools it cannot invoke. Declared scopes are applied first,
whether or not a filter is set - every list omits what this caller would
be refused - so a filter can only hide further, never reveal. Hiding a
primitive does not change what happens if it is called anyway.
cache_ttl_ms sets the freshness hint sent with cacheable results
(tools/list, prompts/list, resources/list, resources/read and
server/discover) on the modern protocol revision; 0 marks them
immediately stale. A list that can differ between callers is additionally
marked private, so a shared proxy cannot serve one caller's answer to
another.
page_size opts the list methods into cursor pagination: each answers
with at most that many entries plus a nextCursor while more remain, so
a large catalogue reaches the agent a page at a time instead of filling
its context in one response. Left unset, every list is answered in full -
a client may ignore nextCursor, so paginating uninvited would hide the
rest of the catalogue from one that does.
tool_search publishes three tools in place of the catalogue -
search_tools, describe_tools and run_tools - so a server with a
large catalogue spends the agent's context on the tools it turns out to
need rather than on every tool it has. run_tools executes declared
calls, not code: each step names a registered tool and its arguments, and
a step's argument may reference an earlier step's result.
session_backend shares HTTP sessions between workers - any object with
async read / write / delete methods over a SessionRecord. Without
one a session lives in the worker that minted it, so a request reaching a
different worker is answered 404 and the client starts a new session.
message_path is the URL an SSE stream names for the client to POST to;
ignored on the other transports.
before_request
¶
Register a function to run before each request.
before_first_request
¶
Register a function to run exactly once on the first request.
A legacy hook style; lifespan startup handlers are preferred. Hooks fire
serially in registration order, and single-fire is guarded with an
asyncio.Lock so concurrent first requests cannot double-run them.
after_request
¶
Register a function to run after each request.
teardown_request
¶
Register a function to run after request teardown.
Called with an optional exception argument, even if an exception occurred.
teardown_appcontext
¶
Register a function to run on app-context teardown.
on_event
¶
Register startup/shutdown event handlers.
Deprecated: use @app.on_startup / @app.on_shutdown instead.
Scheduled for removal in v1.0.0.
add_lifespan
¶
Register an additional lifespan context manager.
lifespan= is a single slot owned by the application, so a plugin or
blueprint uses this to own a resource with paired setup and teardown
without splitting the pair across on_startup / on_shutdown.
factory is called with the app and must return an async context
manager. Every registered lifespan is entered on the same exit stack as
lifespan=, so teardown runs in reverse registration order and teardown
errors are aggregated rather than masking one another. The yielded value
is not consumed - a plugin holds its own handle.
Usage::
class BrokerPlugin:
name = "broker"
def install(self, app):
app.add_lifespan(self.lifespan)
@contextlib.asynccontextmanager
async def lifespan(self, app):
broker = await connect()
try:
yield {"broker": broker}
finally:
await broker.close()
add_event_handler
¶
Imperative event-handler registration - ASGI shape.
Deprecated: call app.on_startup(fn) / app.on_shutdown(fn)
directly instead. Scheduled for removal in v1.0.0.
before_serving
¶
Register a coroutine to run once at app startup. Alias of on_startup.
after_serving
¶
Register a coroutine to run once at app shutdown. Alias of on_shutdown.
endpoint
¶
Attach a function as the view for an already-registered name.
Replaces the existing route's handler in place, which separates route declaration from view registration.
iter_blueprints
¶
Iterate over every registered Blueprint.
In registration order, yielding the objects rather than their names.
shell_context_processor
¶
Register a function returning a dict to merge into veloce shell.
Each processor is called with no args; its dict joins the namespace the interactive shell starts with.
make_shell_context
¶
Build the dict the CLI's shell command drops into.
Always includes app and g; each processor's dict overlays in
registration order, so a later processor wins on conflicts.
url_value_preprocessor
¶
Register a callback that may mutate the matched path params.
Called as fn(endpoint, values) before the handler runs.
Usage::
@app.url_value_preprocessor
def pull_lang(endpoint, values):
from veloce import g
g.lang = values.pop("lang", "en")
endpoint is the route name; values is the path_params dict, and
mutating it in place is the supported way to rewrite them.
url_defaults
¶
Register a callback injecting default kwargs into every URL build.
Called as fn(endpoint, values) from url_for and url_path_for.
Usage::
@app.url_defaults
def add_lang(endpoint, values):
from veloce import g
values.setdefault("lang", g.get("lang", "en"))
Runs in registration order; mutate values in place.
register_error_handler
¶
Register an error handler without a decorator.
The key is an int status code or an exception class. Anything else is
refused: _exception_handlers is matched by walking a raised exception's
MRO, so a non-class key could never be found and would register silently.
exception_handler
¶
Register a custom exception handler by exception type or status code.
add_exception_handler
¶
Imperative exception-handler registration - ASGI shape.
The non-decorator form of @app.exception_handler(...).
Accepts an exception class (matched by MRO at dispatch time) or
an int HTTP status code.
handle_http_exception
async
¶
handle_http_exception(exc: HTTPException, request: Request | None = None) -> Response
Build the response for an HTTPException.
Walks registered status-code + class handlers first (matching abort()
semantics), falling back to JSON
{"detail": exc.detail, "status_code": exc.status_code} with
exc.headers applied - byte-identical to what the request cycle emits,
so a handler reached over MCP reports the error as it does over HTTP.
Pass request= from inside a request scope so the registered handler
receives the real failing request instead of a synthetic GET /.
handle_user_exception
async
¶
Dispatch an arbitrary exception.
HTTPException -> handle_http_exception. Otherwise walks
registered class handlers (MRO); on no match, logs via
log_exception and returns 500. Pass request= to propagate
the real failing request to the registered handler; omit to
get a synthetic GET / for out-of-band callers (background
tasks, CLI hooks).
full_dispatch_request
async
¶
full_dispatch_request(request: Request) -> Any
Dispatch request through the full before/after-request hook chain.
preprocess_request
async
¶
preprocess_request(request: Request) -> Any
Run all before_request hooks for request.
A non-None return short-circuits the chain and becomes the response. App-level hooks fire first, then the matched-blueprint bucket.
process_response
async
¶
Run all after_request hooks for (request, response).
Hooks fire in reverse registration order; each may return a
replacement Response, and any other return keeps the existing one.
This is the dispatch path itself, not a re-implementation.
ensure_sync
staticmethod
¶
Wrap func so it is callable from synchronous code.
A regular function is returned unchanged; a coroutine function comes back wrapped to run on a dedicated event loop. Use it to bridge async handlers into CLI commands, background workers or test scaffolding.
make_response
¶
make_response(value: Any) -> Response
Coerce a handler-return value into a Response.
Accepts (with this coercion table):
- Response -> returned as-is
- str / bytes -> wrapped as a text/HTML response
- dict / list -> wrapped as a JSON response via jsonify
- tuple of (body, status), (body, status, headers) or
(body, headers) -> unpacked and re-coerced
- anything else -> JSON, matching what dispatch does with the same
value returned from a handler
A tuple of any other length is not a response tuple and is answered as a plain value.
add_route
¶
Register a route. See Router.add_route for the full signature.
Brackets the base implementation: refuse a mutation once the app is serving, then drop the caches the new route invalidates. Everything is forwarded untouched.
include_router
¶
include_router(router: Annotated[Router, Doc('Sub-router to mount; a `Blueprint` brings its hooks and handlers with it.')], prefix: Annotated[str, Doc('Path prefix every mounted route is registered under.')] = '', url_prefix: Annotated[str | None, Doc('Blueprint-style spelling of `prefix`; wins when both are given.')] = None) -> None
Mount a sub-router under an optional path prefix.
A Blueprint delegates to register_blueprint, honouring its hooks,
error handlers and url processors; a plain Router delegates to
Router.include_router. url_prefix wins when both are given.
add_instrumentation
¶
add_instrumentation(hook: Callable[..., Any] | None = None, *, exclude_routes: Iterable[str] | None = None) -> Callable[..., Any]
Register an observability instrumentation hook.
hook is called once per finished HTTP request with a RequestMetrics
record - method, concrete path, matched route template, status code
and wall-clock duration in milliseconds. It may be sync or async, and
one that raises is logged and skipped, so instrumentation never breaks
a response.
Returns hook unchanged, so it also works as a decorator, in either
the no-argument or the keyword-argument form:
@app.add_instrumentation
def export(metrics):
statsd.timing(metrics.route or "unmatched", metrics.duration_ms)
@app.add_instrumentation(exclude_routes={"/health"})
def export(metrics):
statsd.timing(metrics.route or "unmatched", metrics.duration_ms)
exclude_routes suppresses this hook for noisy routes - matched route
templates such as {"/health", "/metrics"}. Matching is on the
low-cardinality template resolved during routing, never the concrete
attacker-controlled path, so there is no per-request regex and no
path-normalisation bypass. The filter is applied in the core delivery
loop, so every consumer honours it.
With no hook registered the request path carries no instrumentation cost - not even a clock read.
register_auditable
¶
Register component to report to veloce check and security_audit.
Middleware reports on itself through Middleware.audit, being already
in the stack; this is for something that hardens or exposes the app
without being middleware, such as a mounted MCP endpoint.
component needs an audit(ctx) yielding Findings, and may carry the
Auditable class markers (sets_hardening_headers,
audit_needs_routes). Returns component, so it also decorates.
Usage::
class TelemetryEndpoint:
def audit(self, ctx):
if not self.authenticated:
yield Finding(
"telemetry endpoint accepts unauthenticated writes",
severity="error",
fix="pass auth=...",
id="telemetry-unauthenticated",
)
app.register_auditable(TelemetryEndpoint())
security_audit
¶
Return human-readable warnings about the current security posture.
A rendering of veloce.audit.run(self), whose structured form carries
the severity, remedy and stable id a tool needs. An empty list means
nothing was flagged.
Hardening the app does not own - a reverse proxy terminating TLS - stays invisible, so a clean audit speaks about this app's middleware and not about the deployment around it.
response_contract_audit
¶
Return human-readable findings about each route's response contract.
A rendering of the response-model-contradiction and
routes-undocumented findings from veloce.audit.run(self). A
response_model= naming a different model than the return annotation is
a warning; no contract at all is info, since an HTML page, a redirect
or a stream legitimately has none.
send_static_file
¶
Serve a file from app.static_folder.
app.static_folder defaults to "static", relative to
app.package_root. Returns a FileResponse, traversal-safe via
safe_join. Reads synchronously and warns on a running loop, so async
handlers should prefer send_static_file_async.
send_static_file_async
async
¶
Serve a file from app.static_folder - async variant.
Reads the file in an executor, so it never blocks the event loop.
test_cli_runner
¶
Return a Click CliRunner bound for testing app.cli.
Kwargs flow through to click.testing.CliRunner.
register_blueprint
¶
register_blueprint(blueprint: Annotated[Blueprint, Doc('Blueprint whose routes and hooks are mounted.')], url_prefix: Annotated[str | None, Doc("Path prefix to mount under; defaults to the blueprint's own.")] = None) -> None
Mount a Blueprint's routes + hooks onto this app.
Each route is re-registered under (url_prefix or bp.url_prefix) + path,
so the same blueprint can be mounted twice. Its request hooks and error
handlers are bucketed under its name - a nested child under its dotted
name - so they fire only for that blueprint's own routes, with an
app-level error handler still the fallback. The blueprint itself is left
unmodified, so it can be mounted on several apps.
add_url_rule
¶
add_url_rule(rule: Annotated[str, Doc('URL path template, including `{param}` / `{param:converter}` placeholders.')], endpoint: Annotated[str | None, Doc('Endpoint name for `url_for`; required when registering an endpoint-only stub.')] = None, view_func: Annotated[Callable[..., Any] | None, Doc('Handler for the route; `None` registers an endpoint-only stub for later attachment.')] = None, methods: Annotated[list[str] | None, Doc('HTTP methods this rule serves; defaults to `GET`.')] = None, **kwargs: Any) -> None
Add a URL rule programmatically.
view_func=None registers an endpoint-only stub: the route resolves
for url_for but raises RuntimeError until @app.endpoint(endpoint)
attaches a handler. endpoint is required in that case.
dependency_overrides_provider
¶
Return the dependency override mapping.
Config
¶
Bases: dict[str, Any]
A dict that knows how to load itself from common config sources.
Only keys made of ASCII uppercase letters, digits, or underscores
(and not starting with a digit) are stored - see _is_uppercase_key.
default_config
staticmethod
¶
Return the documented default config keys with their values.
Seeded into app.config at construction so reads never raise KeyError.
from_mapping
¶
Bulk-update from mapping and/or kwargs.
Only UPPERCASE keys are config keys. A non-uppercase keyword argument
raises, since from_mapping(debug=True) would otherwise leave DEBUG
untouched and say nothing; keys in a mapping are filtered quietly, as a
settings dict legitimately carries entries that are not config.
Always returns True so the call can be used as a chaining sentinel.
from_object
¶
Import UPPERCASE attributes from a module, class, instance, or dotted-path string.
from_object("myapp.settings.Prod") resolves the dotted path first.
from_pyfile
¶
Execute a Python file and pull UPPERCASE module-level names.
Returns True on success, or False when silent=True and the file is
missing.
from_env_file
¶
Load KEY=VALUE pairs from a dotenv-style .env file.
Full-line # comments and blank lines are skipped, an optional export
prefix is accepted, and a value wrapped in matching single or double
quotes is unquoted. An unquoted value may carry a trailing # inline
comment, which is stripped; a # inside quotes is kept literal. A value
for a key with a known type is converted to it: DEBUG=false stores
False and MAX_CONTENT_LENGTH=1000 stores 1000, and an unparseable
number raises, naming the key. Only UPPERCASE keys are kept (see
from_mapping). With silent=True a missing file returns False rather
than raising.
Keys are stored exactly as the file spells them, and os.environ is not
touched. This does not compose with from_prefixed_env, which strips its
prefix: a file setting MYAPP_TIMEOUT becomes the config key
MYAPP_TIMEOUT here and TIMEOUT there. Pick one of the two and use it
on every path.
from_envvar
¶
Read a filename from os.environ[varname] and from_pyfile it.
from_prefixed_env
¶
Load config from the env vars named <prefix>_..., less the prefix.
Values are JSON-decoded, falling back to the raw string when JSON
parsing fails. Nested config uses the __ separator:
VELOCE_MAIL__SERVER sets config["MAIL"]["SERVER"].
Reads os.environ only. from_env_file reads a file and keeps each key
verbatim, so the two name the same setting differently - see its note. A
value that is not valid JSON is given the type its key is read as, or
raises by name; a nested key has no declared type and is stored as read.
from_file
¶
from_file(filename: str, load: Callable[[Any], Mapping[str, Any]] = _json_load, silent: bool = False, text: bool = False) -> bool
Load any structured file (JSON, TOML via tomllib.load, YAML ...).
Opens in text or binary mode per text=, hands the file object to
load, and applies the mapping it returns through from_mapping.
get_namespace
¶
get_namespace(namespace: str, *, lowercase: bool = True, trim_namespace: bool = True) -> dict[str, Any]
Return all config keys starting with namespace, trimmed.
With lowercase=True (default) trimmed keys are lower-cased, matching
the attribute names extension code conventionally uses.
Plugin
¶
Bases: Protocol
A Veloce plugin: any object exposing install(self, app).
Usage::
class TimingPlugin:
name = "timing"
def install(self, app):
app.add_instrumentation(self._record)
app.install(TimingPlugin())
HealthPlugin
¶
Serve liveness and readiness probes, and gate readiness on shutdown.
Usage::
from veloce import Veloce
from veloce.health import HealthPlugin
app = Veloce()
health = app.install(HealthPlugin())
@health.readiness_check("cache")
async def cache_ready() -> bool:
return await redis.ping()
/livez reports whether the event loop is running and ignores dependency
checks, because restarting a container cannot fix someone else's database.
/readyz requires startup complete, shutdown not begun, and every check
passing; a failure yields 503 with a per-check body naming what failed.
Checks run concurrently and share one timeout.
readiness_check
¶
readiness_check(name: Annotated[str, Doc('Name reported for this check in the probe body.')]) -> Callable[[ReadinessCheck], ReadinessCheck]
Register a readiness check under name.
The check returns True when this replica can serve traffic. Raising is treated as not-ready, so a check does not need its own try/except.
start_draining
¶
Mark the replica as draining so /readyz starts failing.
Call this when a shutdown signal arrives, before connections are drained. Veloce's own shutdown calls it automatically.
Signals¶
The pub/sub primitives and the eight signals Veloce fires around the request
and app-context lifecycle. Connect a receiver with
request_started.connect(fn); see the
Signals guide for the payload each one carries.
Signal
¶
A named pub/sub signal - standard shape.
send(sender, **kwargs) fires every receiver subscribed for that exact
sender (compared by is, falling back to ==) plus every receiver
subscribed for ANY_SENDER, and returns (receiver, value) pairs.
asend and send_robust_async await async receivers concurrently, with
sync receivers still running inline in registration order first.
connect
¶
Register receiver to fire when send(sender) runs.
sender=ANY_SENDER (the default) subscribes to every send; a specific
sender filters to it. Returns the receiver unchanged, so it can be used
as a decorator.
disconnect
¶
Remove the subscription for (receiver, sender).
Mirrors connect; the default sender=ANY_SENDER removes any
subscription matching receiver whatever sender it was bound to.
A targeted detach matches the stored sender directly rather than
through _matches, which is the send-time rule under which a stored
ANY_SENDER matches every send - reusing it here would delete an
ANY_SENDER subscription whenever the caller targeted one sender.
send
¶
send(sender: Any = None, **kwargs: Any) -> SignalResult
Fire receivers subscribed for sender (and for ANY_SENDER).
Returns (receiver, value) pairs in registration order, and
short-circuits with no subscriptions so callers need not guard with
has_receivers_for. The single live-scan also prunes dead weakrefs.
send_robust
¶
send_robust(sender: Any = None, **kwargs: Any) -> SignalResult
Like send, but never aborts on a failing receiver.
Returns (receiver, value) pairs in registration order, where value
is the return value or the Exception the receiver raised; the
exception is also logged at WARNING.
Sync-only: a receiver returning a coroutine has it closed and a
TypeError recorded instead. Use send_robust_async for async ones.
asend
async
¶
asend(sender: Any = None, **kwargs: Any) -> SignalResult
Async, non-robust send - awaits async receivers concurrently.
Returns (receiver, value) pairs in registration order. Sync receivers
run inline and raise on the first error exactly like send; async ones
are awaited concurrently, each inside a copy of the dispatch-time
context. Use send_robust_async to capture per-receiver failures.
Every async receiver still runs to completion before this coroutine returns or raises - the first exception, in receiver order, is re-raised only once every result is in - so no receiver is still touching request-scoped state afterwards.
send_robust_async
async
¶
send_robust_async(sender: Any = None, **kwargs: Any) -> SignalResult
Async variant of send_robust - awaits async receivers concurrently.
Returns (receiver, value) pairs in registration order, where value
is the return value or the Exception the receiver raised, at call time
or while awaiting; either is also logged at WARNING. One failing
receiver never cancels the others.
receiver_count
¶
How many receivers this signal holds, live or not yet pruned.
Counts what is stored, so a weak reference whose target was collected is
still counted until send prunes it. has_receivers_for answers the
live question instead.
has_receivers_for
¶
True if any connected receiver would fire for sender.
Side-effect-free: dead weakrefs are skipped but not pruned here.
Namespace
¶
A factory that returns named Signal instances, one per name.
Calling signal(name) repeatedly returns the same Signal object, so
independent parts of an application can share one by agreeing on a name.
Usage::
from veloce.signals import Namespace
signals = Namespace()
user_registered = signals.signal("user-registered")
@user_registered.connect
def welcome(sender, **kw):
...
user_registered.send(app, user=user)