Python Deployment Storage
Last Updated: October 23, 2026
Overview
When an app is deployed, Careflow Orchestrator (FlowOps) injects connection details for each storage the image can access as environment variables. Database variables do not say what kind of database they point to, so an app pairs each variable's <label> with the storage metadata from get_deployment() to tell a MongoDB storage from a RabbitMQ one.
The Python sample app implements everything on this page for MongoDB, RabbitMQ and S3 (src/storage). Examples use careflow-sdk 4.0.0, pymongo, pika and boto3.
Environment Variables
<label> is the storage's label exactly as configured in the deployment, including its case, and matches storages[].label in the get_deployment() response. A storage labelled mongo_db gives CAREFLOW_DB_mongo_db_ENDPOINT, so use letters, digits and underscores in labels.
| Variable | Source | Value |
|---|---|---|
CAREFLOW_DB_<label>_ENDPOINT | FlowOps (database storage) | Database host. |
CAREFLOW_DB_<label>_PORT | FlowOps (database storage) | Database port, fixed per engine: 5432 PostgreSQL, 3306 MySQL, 27017 MongoDB, 6379 Redis, 5672 RabbitMQ. |
CAREFLOW_DB_<label>_USERNAME | FlowOps (database storage) | Database user. |
CAREFLOW_DB_<label>_PASSWORD | FlowOps (database storage) | Database password. |
CAREFLOW_BLOB_<label>_BUCKET | FlowOps (blob storage) | Bucket name. |
CAREFLOW_BLOB_<label>_PATH | FlowOps (blob storage) | Key prefix inside the bucket, e.g. /. |
CAREFLOW_BLOB_<label>_PROVIDER | FlowOps (blob storage) | Cloud provider of the bucket, in upper case, e.g. AWS. |
CAREFLOW_BLOB_<label>_ACCESS_ID, _ACCESS_KEY, _REGION_NAME | FlowOps (blob storage) | Credentials and region set on the deployment's storage. Empty unless configured. |
CAREFLOW_BLOB_<label>_ENDPOINT | Set manually (optional) | Not injected by FlowOps. Only needed for an S3-compatible endpoint, e.g. local development. |
CAREFLOW_BLK_<label>_PATH | FlowOps (block storage) | Mount path of the volume, e.g. /mnt/<identifier>. |
An image receives variables for every storage it has access to, including shared storages that are listed under another artifact. When matching labels, search the storages of all artifacts, not just your own.
A database's user is also the name of the database created for it (PostgreSQL, MySQL, MongoDB), and the database starts empty. A block storage disk is mounted read-write before the app starts, keeps its data across restarts and redeployments of the same storage, and is not shared between replicas.
config.yaml
Images built on the Careflow Broker base image also receive the same settings in /careflow/config/config.yaml under storage:: database[] (TYPE, USER, PASSWORD, HOST, PORT, NAME), blob[] (PROVIDER, BUCKET, PATH) and block[] (ROUTE). Database entries carry their TYPE, but no entry carries its label, so with several storages of one kind match them by HOST or BUCKET, or use the environment variables.
Identifying Database Storages
Read the deployment once at startup and map each database storage's label to its DatabaseType:
from careflow_sdk import CareflowClient, ClientOptions
from careflow_sdk.models import DatabaseType, GetDeploymentRequestModel, StorageType
client = CareflowClient(ClientOptions())
deployment = client.app.get_deployment(GetDeploymentRequestModel()).body
database_types_by_label: dict[str, DatabaseType] = {}
models = (deployment.deployment_yaml.models if deployment.deployment_yaml else None) or []
for model in models:
for artifact in model.artifacts or []:
for storage in artifact.storages or []:
if (
storage.storage_type == StorageType.DATABASE
and storage.label
and storage.database_type is not None
):
database_types_by_label.setdefault(storage.label, storage.database_type)Then find the labels that have a CAREFLOW_DB_<label>_ENDPOINT variable and keep the ones of the type you need:
import os
import re
endpoint_pattern = re.compile(r"^CAREFLOW_DB_(?P<label>.+)_ENDPOINT$")
mongo_labels = [
match.group("label")
for match in map(endpoint_pattern.match, os.environ)
if match and database_types_by_label.get(match.group("label")) == DatabaseType.MONGODB
]DatabaseType and StorageType are StrEnums, so storage.database_type == "mongodb" works too. A label with no matching storage, or a type the SDK does not recognise (DatabaseType.UNKNOWN), cannot be classified. The sample app retries get_deployment() up to 3 times at startup and disables MongoDB and RabbitMQ if the deployment cannot be loaded.
MongoDB
The database name and auth source are both the username. Escape the credentials:
import os
from urllib.parse import quote
from pymongo import MongoClient
host = os.environ.get(f"CAREFLOW_DB_{label}_ENDPOINT", "")
port = os.environ.get(f"CAREFLOW_DB_{label}_PORT", "")
user = os.environ.get(f"CAREFLOW_DB_{label}_USERNAME", "")
password = os.environ.get(f"CAREFLOW_DB_{label}_PASSWORD", "")
port_segment = f":{port}" if port else ""
connection_string = (
f"mongodb://{quote(user, safe='')}:{quote(password, safe='')}@{host}{port_segment}"
f"/{user}?authSource={user}"
)
database = MongoClient(connection_string, serverSelectionTimeoutMS=10_000)[user]Skip the storage if ENDPOINT or USERNAME is missing. MongoClient connects lazily, so an unreachable host or wrong credentials surface as a PyMongoError on the first operation; the sample app returns 503 for any PyMongoError.
RabbitMQ
Connecting
Port defaults to 5672 when PORT is missing or not a number. USERNAME and PASSWORD are required.
import os
import pika
port = os.environ.get(f"CAREFLOW_DB_{label}_PORT", "")
parameters = pika.ConnectionParameters(
host=os.environ[f"CAREFLOW_DB_{label}_ENDPOINT"],
port=int(port) if port.isdigit() else 5672,
credentials=pika.PlainCredentials(
os.environ[f"CAREFLOW_DB_{label}_USERNAME"],
os.environ[f"CAREFLOW_DB_{label}_PASSWORD"],
),
client_properties={"connection_name": f"my-app-{label}"},
socket_timeout=10,
stack_timeout=10,
)
connection = pika.BlockingConnection(parameters)Reuse one connection per label and open a channel per operation. A BlockingConnection is not thread-safe, so serialize access to it (the sample app holds a lock per label) and reconnect when it has been closed.
Publishing with Confirms
Put the channel in confirm mode and publish with mandatory=True, so an unconfirmed or unroutable message raises instead of being dropped:
import uuid
channel = connection.channel()
channel.confirm_delivery()
properties = pika.BasicProperties(
message_id=uuid.uuid4().hex,
content_type="application/json",
delivery_mode=pika.DeliveryMode.Persistent,
)
channel.basic_publish(
exchange="", routing_key="my-queue", body=body, properties=properties, mandatory=True
)
channel.close()Consuming
Pull messages with basic_get, then acknowledge them, or reject them back onto the queue:
channel = connection.channel()
method, properties, body = channel.basic_get("my-queue", auto_ack=False)
if method is not None:
payload = body.decode("utf-8")
channel.basic_ack(method.delivery_tag)
channel.close()The sample app reads up to a requested count, then acks (basic_ack) or requeues (basic_nack with requeue=True) everything up to the last delivery tag, both with multiple=True.
Error Cases
All exceptions are in pika.exceptions.
| Exception | Meaning | Sample app response |
|---|---|---|
ProbableAuthenticationError, AuthenticationError, or ConnectionClosedByBroker with reply_code 403, while connecting | Wrong username or password. | 502 |
Any other AMQPConnectionError | Host or port unreachable, or the connection was lost. | 503 |
UnroutableError | No queue matched the exchange and routing key (mandatory=True). | 422 |
NackError | The broker did not confirm the publish. | 502 |
ChannelClosedByBroker | The broker closed the channel. reply_code is 403 (access refused), 404 (queue or exchange not found), 405/406 (resource locked or precondition failed, e.g. redeclaring a queue with different settings). | 403, 404, 409 for 405/406, otherwise 502 |
Queue, exchange and routing key names are limited to 255 bytes.
S3
Blob storages are found by their CAREFLOW_BLOB_<label>_BUCKET variable; they do not need get_deployment(). Object keys are the storage path followed by the file name, without a leading /.
import os
import boto3
from botocore.config import Config
bucket = os.environ[f"CAREFLOW_BLOB_{label}_BUCKET"]
path = os.environ.get(f"CAREFLOW_BLOB_{label}_PATH") or "/"
endpoint = os.environ.get(f"CAREFLOW_BLOB_{label}_ENDPOINT")
region = os.environ.get(f"CAREFLOW_BLOB_{label}_REGION_NAME")
access_id = os.environ.get(f"CAREFLOW_BLOB_{label}_ACCESS_ID")
access_key = os.environ.get(f"CAREFLOW_BLOB_{label}_ACCESS_KEY")
settings = {}
if endpoint:
settings["endpoint_url"] = endpoint
settings["config"] = Config(s3={"addressing_style": "path"})
elif region:
settings["region_name"] = region
if access_id and access_key:
settings["aws_access_key_id"] = access_id
settings["aws_secret_access_key"] = access_key
s3 = boto3.client("s3", **settings)
s3.put_object(
Bucket=bucket,
Key=f"{path}{file_name}".lstrip("/"),
Body=content,
ContentType=content_type,
)On a Careflow deployment ACCESS_ID and ACCESS_KEY are normally empty and ENDPOINT is not set, so the client uses the default AWS credential chain. That picks up the IAM role FlowOps gives the image, which can list each of its buckets and read, write and delete objects under the storage's PATH; access outside PATH is denied. The sample app returns 502 for a botocore ClientError or BotoCoreError.