Skip to main content

Kestra Python Client

This Python client provides functionality to interact with the Kestra server for sending metrics, outputs, and logs, as well as executing/polling flows.

Installation

pip install kestra

Kestra Class

The Kestra class is responsible for sending metrics, outputs, and logs to the Kestra server.

Methods

  • _send(map_: dict): Sends a message to the Kestra server (flushes stdout immediately).
  • format(map_: dict) -> str: Formats a message to be sent to the Kestra server (::{"...": ...}::).
  • _metrics(name: str, type_: str, value: int | float, tags: Mapping | None = None): Sends a metric to the Kestra server. Validates that name is a non-empty string, value is a finite number (rejecting NaN, Inf, and booleans with ValueError), and tags are single stringifiable values.
  • outputs(map_: Mapping): Sends key-value outputs to the Kestra server. Requires a dictionary (empty mapping is a no-op). Dates, datetimes and times are sent as ISO 8601 text, and a value JSON cannot hold raises an error that says what to pass.
  • assets(map_: Mapping): Sends assets to the Kestra server. Requires a dictionary (empty mapping is a no-op).
  • counter(name: str, value: int | float, tags: Mapping | None = None): Sends a counter to the Kestra server.
  • timer(name: str, duration: int | float | Callable, tags: Mapping | None = None): Sends a timer in seconds to the Kestra server. If duration is a callable, it measures the elapsed time in seconds, records the metric, and returns the callable's return value. The name and tags are checked before the callable runs, and no metric is sent when it raises.
  • gauge(name: str, value: int | float, tags: Mapping | None = None): Sends a gauge to the Kestra server.
  • logger() -> Logger: Retrieves the logger for the Kestra server.

Flow Class

The Flow class is used to execute a Kestra flow and optionally wait for its completion. It can also be used to get the status of an execution and the logs of an execution.

Initialization

flow = Flow(
  wait_for_completion=True, # default is True
  poll_interval=1, # seconds. default is 1  
  labels_from_inputs=False, # default is False
  tenant=None # default is None
)

You can also set the hostname and authentication credentials using environment variables:

export KESTRA_HOSTNAME=http://localhost:8080
export KESTRA_USER=admin
export KESTRA_PASSWORD=admin
export KESTRA_API_TOKEN=my_api_token

It is worth noting that the KESTRA_API_TOKEN or KESTRA_USER and KESTRA_PASSWORD need to be used, you do not need all at once. The possible Authentication patterns are:

  1. KESTRA_API_TOKEN
  2. KESTRA_USER and KESTRA_PASSWORD
  3. No Authentication (not recommended for production environments)

Methods

  • _make_request(method: str, url: str, **kwargs) -> requests.Response: Makes a request to the Kestra server with optional authentication and retries.
  • check_status(execution_id: str) -> requests.Response: Checks the status of an execution.
  • get_logs(execution_id: str) -> requests.Response: Retrieves the logs of an execution.
  • execute(namespace: str, flow: str, inputs: dict = None) -> namedtuple: Executes a Kestra flow and optionally waits for its completion. The namedtuple returned is a namedtuple with the following properties:
    • status: The status of the execution.
    • log: The log of the execution.
    • error: The error of the execution.

Usage Examples

  1. Trigger a flow and wait for its completion:

    from kestra import Flow
    flow = Flow()
    flow.execute('mynamespace', 'myflow', {'param': 'value'})
    
  2. Set labels from inputs:

    from kestra import Flow
    flow = Flow(labels_from_inputs=True)
    flow.execute('mynamespace', 'myflow', {'param': 'value'})
    
  3. Pass a text file to an input of type FILE named 'myfile':

    from kestra import Flow
    flow = Flow()
    with open('example.txt', 'rb') as fh:
        flow.execute('mynamespace', 'myflow', {'files': ('myfile', fh, 'text/plain')})
    
  4. Fire and forget:

    from kestra import Flow
    flow = Flow(wait_for_completion=False)
    flow.execute('mynamespace', 'myflow', {'param': 'value'})
    
  5. Overwrite the username and password:

    from kestra import Flow
    flow = Flow()
    flow.user = 'admin'
    flow.password = 'admin'
    flow.execute('mynamespace', 'myflow')
    
  6. Set the hostname, username, and password using environment variables:

    from kestra import Flow
    import os
    
    os.environ["KESTRA_HOSTNAME"] = "http://localhost:8080"
    os.environ["KESTRA_USER"] = "admin"
    os.environ["KESTRA_PASSWORD"] = "admin"
    flow = Flow()
    flow.execute('mynamespace', 'myflow', {'param': 'value'})
    

Error Handling

The client includes retry logic with exponential backoff for certain HTTP status codes, and raises a FailedExponentialBackoff exception if the request fails after multiple retries.

Kestra Class

Logging

The Kestra class provides a logger that formats logs in JSON format, making it easier to integrate with log management systems.

from kestra import Kestra

Kestra.logger().info("Hello, world!")

Outputs

The Kestra class provides a method to send key-value-based outputs to the Kestra server. If you want to output large objects, write them to a file and specify them within the outputFiles property of the Python script task.

Kestra.outputs({"my_output": "my_value"})

Counters

The Kestra class provides a method to send counter metrics to the Kestra server.

Kestra.counter("my_counter", 1)

Timers

The Kestra class provides a method to send timer metrics in seconds to the Kestra server. You can pass a duration in seconds, or pass a callable: timer() will measure the execution time in seconds, record the timer metric, and return the callable's return value.

# Pass duration directly in seconds
Kestra.timer("my_timer", 1.5)

# Time a callable function and receive its result
result = Kestra.timer("compute_duration", lambda: sum(range(1000)))

Gauges

The Kestra class provides a method to send gauge metrics to the Kestra server.

Kestra.gauge("my_gauge", 42.5)

Execution Context

The context object exposes the metadata of the current execution, so scripts stay plain Python instead of embedding Pebble expressions:

import pandas as pd
from kestra import context

my_labels = context.labels
my_inputs = context.inputs
my_vars = context.vars
start_date = context.trigger.startDate
csv_path = context.outputs.prev_task.uri  # outputs from previous tasks

df = pd.read_csv(csv_path)

The context is read from the .kestra-execution-context.json file that Kestra injects into the task working directory. Use KESTRA_EXECUTION_CONTEXT_FILE to read it from another path, or set the base64-encoded KESTRA_CONTEXT environment variable when no file is available. That fallback does not apply to load_execution_context(path): a path that does not exist raises FileNotFoundError.

It is loaded lazily on first access and raises a FileNotFoundError when the script does not run inside a Kestra task. A directory or an unreadable file raises its read error. A ValueError says whether KESTRA_CONTEXT is not base64, or the context is not valid JSON or not a JSON object.

Nested objects are wrapped, including those inside lists, so any depth can be traversed with attributes: context.inputs.my_list[0].my_key.

context is a read-only Mapping, so len(), in, iteration, keys(), values(), items(), get() and dict(context) all work as expected.

Methods

  • context[name]: Same as attribute access. Required for keys that are not valid Python identifiers, or that collide with a method name such as context["items"].
  • context.get(name, default=None): Returns default instead of raising when the key is missing.
  • context.to_dict(): Returns a copy of the context as a plain dict, ready for json.dumps. Changing it does not change context.
  • load_execution_context(path=None) -> ExecutionContext: Loads the context explicitly, from path when given. A path that does not exist raises FileNotFoundError instead of falling back to KESTRA_CONTEXT.

Kestra Ion

The Kestra ION extra provides a method to read files and convert them to a list of dictionaries.

Installation

pip install kestra[ion]

Methods

  • read(path_: str) -> list[dict[str, Any]]: Reads an Ion file and converts it to a list of dictionaries.

Usage Example

import pandas as pd
import requests
from kestra import Kestra

file_path = "employees.ion"
url = "https://huggingface.co/datasets/kestra/datasets/resolve/main/ion/employees.ion"
response = requests.get(url)
if response.status_code == 200:
    with open(file_path, "wb") as file:
        file.write(response.content)
else:
    print(f"Failed to download the file. Status code: {response.status_code}")


data = Kestra.read(file_path)
df = pd.DataFrame(data)
print(df.info())

Metadata

Release files for kestra 2.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 kestra 2.1.0
File Size Uploaded Provenance Actions
kestra-2.1.0.tar.gz 19.4 kB Without provenance Details for kestra-2.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for kestra 2.1.0
File Interpreter ABI Platform Actions
kestra-2.1.0-py3-none-any.whl Python 3 none any Details for kestra-2.1.0-py3-none-any.whl

Total release size: 32.5 kB

Release files / kestra-2.1.0.tar.gz

Download URL kestra-2.1.0.tar.gz
Size 19.4 kB
Tags Source
SHA-256 checksum
How to use checksums
4c592fe9601490b6c66d10af66bbc4546f87c6cd88f470914acae6849f6ce06c
BLAKE2b-256 checksum
How to use checksums
5ad5273bacab6c94e07547007a7cbf013c6e5aec0da8a728f4f7d55ef2f13824
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / kestra-2.1.0-py3-none-any.whl

Download URL kestra-2.1.0-py3-none-any.whl
Size 13.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
716714ca8c6d05a8447fb3b3a4f459b29da56003ba03d6fc1ab5fd2e2ce58015
BLAKE2b-256 checksum
How to use checksums
93ced243ea96130412ef135e66d5dff7616f59887f405a05e6ecb2f129b42dc6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for kestra 2.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.

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