| [ Web Proxy ] |
| Viewing: https://render.com/docs/workflows-sdk-python | [Back] [Original] |
The Render SDK for Python provides support for:
When triggering runs, you use different classes for asynchronous and synchronous execution contexts.
From your Python project directory:
If you already have the SDK installed, make sure you're using version 1.0.1 or later:
After installing, make sure to add render>=1.0.1 as a dependency in your application's requirements.txt, pyproject.toml, or equivalent.
The following symbols pertain to creating and registering tasks in your workflow service. For guidance on how to use them, see Defining Workflow Tasks.
Workflows classHandles defining and registering workflow tasks. Initialize this in each file where you define tasks.
Initializes a new Workflows object. All arguments are optional.
| Argument | Description | ||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
A Individual tasks can override this. | ||||||||||||||||||||||||
|
The default timeout (in seconds) for all tasks in this workflow. Individual tasks can override this. | ||||||||||||||||||||||||
|
The default compute plan to use for all tasks in this workflow. Individual task definitions can override this. One of the following:
The default value is |
Initializes a new Workflows object that incorporates tasks from one or more other Workflows objects.
Use this in your workflow's entry point file if you import task definitions from other files:
If you set any defaults with this method (such as default_timeout), those defaults apply only to tasks registered directly on this Workflows object (not to tasks registered on the imported objects).
| Argument | Description |
|---|---|
|
Required. One or more If two objects define a task with the same name, this raises a |
|
The default retry configuration for new tasks registered on this workflow. Same as the |
|
The default timeout for new tasks registered on this workflow. Same as the |
|
The default compute plan for new tasks registered on this workflow. Same as the |
@app.task decoratorYou apply the @app.task decorator to a Python function to register it as a workflow task. For details, see Defining Workflow Tasks
| Option | Description | ||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
Task decorator arguments | |||||||||||||||||||||||||
|
A custom name for the task. This affects the task's slug, which you use to reference the task when triggering runs. If omitted, defaults to the name of the decorated function. | ||||||||||||||||||||||||
|
A | ||||||||||||||||||||||||
|
The timeout for the task's runs, in seconds. Must be between 30 seconds ( The default value is 2 hours. | ||||||||||||||||||||||||
|
The compute plan to use for the task's runs. One of the following:
The default value is | ||||||||||||||||||||||||
|
Retry arguments | |||||||||||||||||||||||||
|
The maximum number of retries to attempt for a given run of the task. The total number of attempts is up to | ||||||||||||||||||||||||
|
The base delay before attempting the first retry, in milliseconds. | ||||||||||||||||||||||||
|
The exponential backoff factor. After each retry, the previous delay is multiplied by this factor. For example, a factor of
| ||||||||||||||||||||||||
TaskContext objectEvery task function must accept a TaskContext object as its first positional argument. Render automatically provides this object to each run (you do not provide it as an input).
The TaskContext object provides a single method, run(), which you use for run chaining:
Chains a run of the specified task on a separate instance.
On success: Returns the chained run's return value.
Raises: TaskRunError, ValueError
| Argument | Description |
|---|---|
|
Required. The |
|
All input arguments to pass to the task run, as positional arguments: You cannot provide both positional and named task arguments in the same call (this raises a |
|
All input arguments to pass to the task run, as named arguments: You cannot provide both positional and named task arguments in the same call (this raises a |
app.start() methodThe app.start() method serves as the entry point for your workflow during both task registration and run execution. Your workflow definition must call this method as part of startup:
This method takes no arguments.
RenderAsync classUse the RenderAsync class to trigger and manage task runs from any asynchronous execution context (such as a FastAPI route handler). Except where indicated, all methods are async and return awaitable objects.
Initializes a new RenderAsync object. All arguments are optional.
| Argument | Description |
|---|---|
|
The API key to use for authentication. If omitted, the client automatically detects and uses the value of the |
These methods are available on the workflows attribute of the RenderAsync class.
Kicks off a run of the registered task with the specified identifier, passing the specified arguments.
To instead run a task and wait for it to complete, use workflows.run_task.
On success: Returns an AwaitableTaskRun object representing the initial state of the task run. You can await this object to wait for the run to complete.
Raises: ClientError, ServerError, TimeoutError
| Argument | Description |
|---|---|
|
Required. The slug indicating the task to run, available from your task's page in the Render Dashboard: Always has the format |
|
Required. A list or dictionary containing the task's input arguments.:
For a task that takes zero arguments, provide an empty list, |
Starts the registered task with the specified identifier, waits for it to complete, and returns the result.
To instead kick off a run without waiting for it to complete, use workflows.start_task.
On success: Returns a TaskRunDetails object for the completed task run.
Raises: ClientError, ServerError, TimeoutError, TaskRunError
| Argument | Description |
|---|---|
|
Required. The slug indicating the task to run, available from your task's page in the Render Dashboard: Always has the format |
|
Required. A list or dictionary containing the task's input arguments.:
For a task that takes zero arguments, provide an empty list, |
Lists task runs that match optional filters specified in the provided ListTaskRunsParams object.
On success: Returns a list of TaskRunWithCursor objects.
Raises: ClientError, ServerError, TimeoutError
Supported fields of the ListTaskRunsParams object include:
Retrieves the details of the task run with the specified ID.
On success: Returns a TaskRunDetails object.
Raises: ClientError, ServerError, TimeoutError
Cancels the root-level task run with the specified ID, along with all of its chained runs. This raises a ClientError if the root-level run is not found, or if it isn't currently running.
On success: Returns None.
Raises: ClientError, ServerError, TimeoutError
Streams terminal-status events for one or more task runs via Server-Sent Events (SSE). Returns an async iterator that yields a TaskRunDetails object each time a specified task run reaches a terminal status (such as completed, failed, or canceled).
The connection stays open until all events are received or you break out of the loop.
Raises: ClientError, ServerError, TimeoutError
AwaitableTaskRun classRepresents the initial state of a task run as returned by the async workflows.start_task method.
You can await this object to wait for the task run to complete. On success, it returns a TaskRunDetails object:
If the task run fails, this await raises a TaskRunError exception.
| Property | Description |
|---|---|
|
The ID of the task run. Has the format |
|
The initial status of the task run. This is usually |
Render classUse the Render class in any synchronous execution context (such as a default Flask or Django app). Except where indicated, all methods are blocking.
Initializes a new Render object. All arguments are optional.
| Argument | Description |
|---|---|
|
The API key to use for authentication. If omitted, the client automatically detects and uses the value of the |
These methods are available on the workflows attribute of the Render class.
Runs the registered task with the specified identifier, passing the specified arguments.
To instead run a task and wait for it to complete, use workflows.run_task.
On success: Returns a TaskRun object representing the initial state of the task run (e.g. id, status). To wait for completion, poll workflows.get_task_run or use workflows.run_task.
Raises: ClientError, ServerError, TimeoutError
| Argument | Description |
|---|---|
|
Required. The slug indicating the task to run. Format: |
|
Required. A list or dictionary containing the task's input arguments. For zero arguments, use |
Starts the task, waits for it to complete, and returns the result.
To instead kick off a run without waiting for it to complete, use workflows.start_task.
On success: Returns a TaskRunDetails object.
Raises: ClientError, ServerError, TimeoutError, TaskRunError
| Argument | Description |
|---|---|
|
Required. The slug indicating the task to run. Format: |
|
Required. A list or dictionary containing the task's input arguments. For zero arguments, use |
Lists task runs that match optional filters.
On success: Returns a list of TaskRunWithCursor objects.
Raises: ClientError, ServerError, TimeoutError
Supported fields: limit, cursor, owner_id. See workflows.list_task_runs for parameter descriptions.
Retrieves the details of the task run with the specified ID.
On success: Returns a TaskRunDetails object.
Raises: ClientError, ServerError, TimeoutError
Cancels the root-level task run, along with all of its chained runs. Raises ClientError if the root-level run is not found or not running.
On success: Returns None.
Raises: ClientError, ServerError, TimeoutError
Streams terminal-status events via SSE. Returns a synchronous iterator that yields a TaskRunDetails object each time a specified task run reaches a terminal status (such as completed, failed, or canceled).
Raises: ClientError, ServerError, TimeoutError
TaskRunWithCursor classRepresents an item returned by workflows.list_task_runs (sync or async). It pairs a task run with the cursor for that item.
| Property | Description |
|---|---|
|
The |
|
The cursor associated with this item. Provide it in |
TaskRun classSummarizes the state of a task run. Obtained in one of the following ways:
workflows.start_task methodtask_run property of a TaskRunWithCursor returned by workflows.list_task_runs (sync or async)To get a run's full details including results, call workflows.get_task_run (sync or async) and provide the run's ID to obtain a TaskRunDetails object.
TaskRunDetails classProvides the full details of a task run. Obtained in one of the following ways:
awaiting an AwaitableTaskRun object returned by the async workflows.start_task method:
Calling the workflows.run_task method of the Render or RenderAsync class:
Calling the workflows.get_task_run method of the Render or RenderAsync class:
Iterating over events from the workflows.task_run_events method of the Render or RenderAsync class:
A TaskRunDetails object includes all of the same properties as a TaskRun object, plus:
| Property | Description |
|---|---|
|
A list containing the task's return value(s). This value is always an empty list if |
|
The argument values that were passed to the task run, in the same format they were provided (as a list or a dictionary). Note the trailing underscore ( |
|
The error message if the task run failed. Present only if |
|
A list of |
The Render SDK defines the custom exception types listed below. RenderError is the parent class for all other custom exception types.
In certain cases, the SDK also raises standard Python exceptions, such as ValueError and TypeError.
| Exception | Description |
|---|---|
|
The base class for all exceptions raised by the SDK. |
|
Raised when a request to the Render API returns a 400-level error code. Common causes include:
|
|
A subclass of |
|
Raised when a request to the Render API returns a 500-level error code. |
|
Raised when a request to the Render API times out. |
|
Raised when a task run fails, such as when |
$ pip install render
$ pip install --upgrade render
from render import Workflows, Retry# Basic initializationapp = Workflows()# Initialization with all options setapp = Workflows(default_retry=Retry(max_retries=3,wait_duration_ms=1000,backoff_scaling=1.5),default_timeout=300,default_plan="flex")
from render import Workflowsfrom math_tasks import app as math_appfrom text_tasks import app as text_appapp = Workflows.from_workflows(math_app, text_app)if __name__ == "__main__":app.start()
from render import TaskContext, Workflowsapp = Workflows()@app.taskdef calculate_square(ctx: TaskContext, a: int) -> int:return a * a
from render import Retry, TaskContext, Workflowsapp = Workflows()@app.task(name="calc_square", # Give the task a custom name (defaults to function name)retry=Retry( # Define default retry logic for the taskmax_retries=3, # Retry up to 3 times (i.e., 4 total attempts)wait_duration_ms=1000, # Set a base retry delay of 1 secondbackoff_scaling=1.5 # Increase delay by 50% after each retry (exponential backoff)),timeout_seconds=300, # Timeout in secondsplan="2c-4g" # Compute plan)def calculate_square(ctx: TaskContext, a: int) -> int:return a * a
import asyncio@app.taskasync def sum_squares(ctx: TaskContext, a: int, b: int) -> int:first, second = await asyncio.gather(ctx.run(calculate_square, a),ctx.run(calculate_square, b))return first + second
ctx.run(sum_squares, 2, 3)
ctx.run(sum_squares, a=2, b=3)
from render import TaskContext, Workflowsapp = Workflows()@app.taskdef calculate_square(ctx: TaskContext, a: int) -> int:return a * aif __name__ == "__main__":app.start()
from render import RenderAsync# Basic initializationrender = RenderAsync()# Initialization with API keyrender = RenderAsync(token="rnd_abc123")
# Execute the calculate_square task with an input of 2started_task_run = await render.workflows.start_task("my-workflow/calculate_square",[2])task_run_id = started_task_run.id # ID is available immediatelytask_run_status = started_task_run.status # Initial status is available immediatelyfinished_task_run = await started_task_run # Other properties become available after the task run completesprint(finished_task_run.results) # Prints the task run's result, in this case [4]
# Run the calculate_square task and wait for the resulttask_run = await render.workflows.run_task("my-workflow/calculate_square",[2])print(task_run.results) # [4]
from render.client.types import ListTaskRunsParamsparams = ListTaskRunsParams(limit=10, # Return up to 10 runscursor="cfQ74cE2sDI=", # Start from this cursorowner_id=["tea-d3jm7ai4d50c73fale60"] # Limit to these workspace IDs)task_runs = await render.workflows.list_task_runs(params)for item in task_runs:print(item.task_run.id, item.cursor)
await render.workflows.get_task_run("trn-abc123")
await render.workflows.cancel_task_run("trn-abc123")
# Start multiple tasksrun1 = await render.workflows.start_task("my-workflow/add", [1, 2])run2 = await render.workflows.start_task("my-workflow/add", [5, 8])# Stream events until all runs completepending = {run1.id, run2.id}async for event in render.workflows.task_run_events(list(pending)):print(f"Run {event.id}: status={event.status}")pending.discard(event.id)if not pending:break
started_task_run = await render.workflows.start_task("my-workflow/calculate_square",[2])finished_task_run = await started_task_run
from render import Render# Basic initializationrender = Render()# Initialization with API keyrender = Render(token="rnd_abc123")
started_task_run = render.workflows.start_task("my-workflow/calculate_square",[2])# Poll with get_task_run(started_task_run.id) or use run_task() to block until done
task_run = render.workflows.run_task("my-workflow/calculate_square", [2])print(task_run.results)
from render.client.types import ListTaskRunsParamsparams = ListTaskRunsParams(limit=10, cursor="", owner_id=["tea-"])task_runs = render.workflows.list_task_runs(params)for item in task_runs:print(item.task_run.id, item.cursor)
render.workflows.get_task_run("trn-abc123")
render.workflows.cancel_task_run("trn-abc123")
for event in render.workflows.task_run_events(["trn-abc123"]):print(f"Run {event.id}: status={event.status}")
started_task_run = await render.workflows.start_task("my-workflow/calculate_square",[2])finished_task_run = await started_task_run
task_run_details = await render.workflows.run_task("my-workflow/calculate_square", [2])
task_run_details = await render.workflows.get_task_run("trn-abc123")
async for event in render.workflows.task_run_events(["trn-abc123"]):task_run_details = event
from render.client.errors import (RenderError, # Parent class for other exceptionsClientError,RateLimitError,ServerError,TimeoutError,TaskRunError)
| Web Proxy Viewer | New URL | Original Page |