Skip to main content

bw-essentials

Here’s a rephrased version of your description with improved flow and clarity:


bw-essentials is a Python utility package offering modular and production-ready wrappers for core infrastructure tasks. It simplifies operations such as AWS S3 interactions, email notifications, and version-controlled data lake workflows using LakeFS. Designed for flexibility and ease of integration, it's well-suited for use across microservices, data pipelines, and automation frameworks.

In addition to infrastructure utilities, it also includes service-specific wrappers for:

  1. Master Data
  2. Market Pricer
  3. Broker
  4. Model Portfolio Reporting
  5. Trade Placement
  6. User Portfolio
  7. User Portfolio Reporting
  8. Portfolio Business (payment-gateway configuration)
  9. Portfolio Product (Django content and catalogue APIs)

ApiClient

Synchronous ApiClient requests default to a 30-second timeout; pass timeout= to _request to override it per call.


Portfolio Business client

PortfolioBusiness fetches an analyst's payment-gateway configuration using service-to-service authentication. Configure PORTFOLIO_BUSINESS_BASE_URL as the service origin (without /business/portfolio) and set PORTFOLIO_BUSINESS_API_KEY; the client sends the key as X-API-Key.

from bw_essentials.services.portfolio_business import PortfolioBusiness

client = PortfolioBusiness(service_user="payment-service")
gateway_config = client.get_payment_gateway_secrets("analyst-id")

Response credentials are redacted from HTTP logs.


Portfolio Product client

PortfolioProduct covers the Django content and catalogue APIs. Configure PORTFOLIO_PRODUCT_BASE_URL as the service root (for example, http://host:8000/portfolio-product) and use set_tenant_id() for tenant selection; an unknown tenant falls back to the server default. Requests and responses use snake_case, and methods return the unwrapped response data. HTTP errors and missing data keys propagate to callers, while response bodies are redacted from logs.

The server returns HTTP 404 for empty rebalance or subscription history. Subscription plan_notes must be an object or an array, and portfolio exchange should be supplied because its database column is NOT NULL even though validation marks it optional. The existing PortfolioContent and PortfolioCatalogue clients remain unchanged for the Node services.

from bw_essentials.services.portfolio_product import PortfolioProduct

client = PortfolioProduct(service_user="recommendations-api")
client.set_tenant_id("ysl")
portfolios = client.list_portfolios(status="active", broker="ysl")

Notification Service client

NotificationService targets the Django notification service for WhatsApp, SMS, and e-mail. Configure NOTIFICATION_BASE_URL as the complete service root including /notification (for example, http://host:8000/notification), plus NOTIFICATION_API_KEY, NOTIFICATION_SENDER_NUMBER, and PLATFORM. Select a tenant with tenant_id= when constructing the client or later with set_tenant_id().

Requests use the Django service's snake_case JSON contract, and send methods return the unwrapped response data. Non-2xx responses raise NotificationServiceError, a requests.HTTPError subclass whose status_code, code, message, and details fields expose the decoded error; its string form deliberately excludes details and the echoed request payload.

from bw_essentials.services.notification import NotificationService

client = NotificationService(tenant_id="demo")
result = client.send_email(
    title="Account update",
    content="Your account was updated.",
    to="user@example.com",
    user_id="USR1",
)

This client targets the Django service; the Node service rejects user_id as an unknown key, so consumers must bump this library only after the Django cut-over.


📦 Installation

pip install bw-essentials

📁 S3Utils

S3Utils provides a high-level interface to interact with AWS S3 and S3-compatible services like MinIO or LocalStack.

🔧 Initialization

from bw_essentials.s3_utils import S3Utils

s3 = S3Utils()

✅ Available Methods

Method Description
upload_file(bucket, key, file_path) Upload a local file to S3
download_file(bucket, key, dest_path) Download a file from S3
list_files(bucket, prefix="") List all files under a prefix
read_file(bucket, key) Read and return the content of a file
delete_file(bucket, key) Delete a specific file
file_exists(bucket, key) Check if a file exists
get_latest_file(bucket, prefix) Get the latest file by modified time
sync_local_to_s3(bucket, prefix, local_path) Recursively upload a local directory to S3
sync_s3_to_local(bucket, prefix, local_path) Recursively download an S3 prefix to local
generate_presigned_url(bucket_name, object_key, expiration) Generates Pre Signed Url for given S3 Object.

📬 EmailClient

EmailClient helps send email notifications with or without attachments using any SMTP server.

🔧 Initialization

from bw_essentials.email_client import EmailClient

client = EmailClient(
    sender_email="noreply@example.com",
    sender_name="BW Notifier"
)

✅ Available Methods

Method Description
send_email_without_attachment(to_addresses, cc_addresses, subject, body, is_html=True) Send an email without attachment
send_email_with_attachment(to_addresses, cc_addresses, subject, body, attachment_path, is_html=True) Send an email with a file attachment
  • Supports both plain text and HTML.
  • Accepts single or multiple recipients (str or List[str]).
  • Gracefully handles invalid paths and logs detailed errors.

🏞️ DataLoch (LakeFS Wrapper)

DataLoch wraps LakeFS Python client for working with versioned data over S3. Useful for managing commits, branches, and file operations in a data lake.

🔧 Initialization

from bw_essentials.data_loch import LakeFS

dl = LakeFS()

You can pass branch and repo to individual methods or initialize them via dl.repo = "repo" and dl.branch = "branch".

✅ Available Methods

Method Description
upload_file(local_path, repo, branch, dest_path) Upload a single file to a branch
download_file(repo, branch, file_path, dest_path) Download a single file
sync_local_to_lakefs(local_path, repo, branch, dest_prefix) Recursively upload a directory
sync_lakefs_to_local(repo, branch, src_prefix, local_path) Recursively download a directory
commit(repo, branch, message) Commit the current changes on a branch
get_latest_file(repo, branch, prefix) Get latest file (by time) under a prefix
delete_file(repo, branch, file_path) Delete a specific file
  • Supports S3-compatible object storage behind LakeFS.
  • Handles versioning and commit messages for reproducibility.

🧪 Example Use Case

# Send notification with S3 report
from bw_essentials.s3_utils import S3Utils
from bw_essentials.email_client import EmailClient

s3 = S3Utils("AK", "SK")
file_path = "/tmp/report.csv"
s3.download_file("my-bucket", "reports/weekly.csv", file_path)

email_client = EmailClient("me@example.com", "Report Bot")
email_client.send_email_with_attachment(
    to_addresses="client@example.com",
    cc_addresses=["ops@example.com"],
    subject="Weekly Report",
    body="<h1>Attached is your report</h1>",
    attachment_path=file_path
)

Here’s the updated setup.py with a module docstring and updated dependencies:

🔔 Notifications

Notifications helps send structured alerts and logs to external communication tools like Microsoft Teams and Zenduty. Ideal for operational awareness and incident response workflows.

🔧 Initialization

from bw_essentials.notifications import Notifications

notifier = Notifications(
    title="BW Alerts",
    summary="Pipeline Failure",
    message="Daily data sync failed.",
    webhook_url="https://sample.webhook.url"
)

✅ Available Methods

Method Description
notify_message(message=None, summary=None, alert=False) Send a general log message to Teams
notify_error(message=None, summary=None, alert=True, trace=None, request_id=None) Send an error alert to Teams and Zenduty
  • Automatically uses different formats for logs vs. alerts.
  • Teams messages are sent via Adaptive Cards.
  • Zenduty alerts include critical summaries and tracebacks.
  • You can override the default message, summary, trace, and request_id per notification.

📘 Example Use Case

notifier.notify_error(
    message="ETL job failed due to timeout.",
    summary="Job: daily-prices-sync",
    trace="Traceback (most recent call last): ...",
    request_id="req-123abc"
)

SigNoz Observability

OpenTelemetry dependencies are included in the core installation. The observability extra remains available as a compatibility alias:

pip install "bw-essentials-core[observability]"

Django imports:

from bw_essentials.observability.django.otel import (
    DjangoOTelService,
    build_sanitized_request_context,
    configure_celery_tracing,
    configure_otel_logging,
    init_otel,
)

FastAPI imports:

from bw_essentials.observability.fastapi.otel import (
    FastAPIOTelService,
    build_sanitized_fastapi_request_context,
    init_fastapi_otel,
)

The observability helpers are split by framework: Django startup lives in bw_essentials.observability.django.otel, FastAPI startup lives in bw_essentials.observability.fastapi.otel, and common sanitization/export utilities live in bw_essentials.observability.services.

These helpers provide idempotent OTel startup, trace-correlated log export, safe outbound HTTP span URLs without query strings, sanitized request-context helpers that can be called from each service's existing request middleware, and FastAPI instrumentation for requests/httpx/Redis/SQLAlchemy.

Upgrading to 0.2

Read the complete Observability 0.2 migration guide before changing a service pin. It includes the process-by-process adoption checklist and the atomic rollback recipe.

Version 0.2 defaults OTLP export to HTTP/protobuf. If an existing deployment uses the former gRPC port :4317, either move OTEL_EXPORTER_OTLP_ENDPOINT to :4318, or keep :4317 and set OTEL_EXPORTER_OTLP_PROTOCOL=grpc. The inverse mismatch also fails: gRPC on :4318 must move to :4317 or set OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf.

OpenTelemetry process lifecycle

OpenTelemetry must be initialized in each worker process, never in a Gunicorn master. Do not use Gunicorn --preload. Django deployments should expose the provided hook from gunicorn.conf.py:

from bw_essentials.observability.gunicorn import post_worker_init

post_worker_init runs after the application is loaded and after worker-specific monkey patching. It detects configured Django or a loaded FastAPI app in the worker and initializes the matching adapter. FastAPI/ASGI deployments whose worker does not expose the app can still call init_fastapi_otel(app) during application startup. The initializers are idempotent per PID. They default to OTLP/HTTP protobuf, 100% head sampling, bounded export queues, and exact path- segment exclusions for health, healthz, health_check, ready, readyz, live, livez, metrics, and ping. Set the standard framework-specific or generic OTEL_PYTHON_*_EXCLUDED_URLS variable to override those exclusions.

Django stdlib sinks and access logs

Every Django console, file, rotating-file, and CloudWatch handler must use bw_essentials.observability.logging.SafeFormatter. A formatter is required on each handler because one shared LogRecord can be delivered to several sinks; the safe formatter redacts a copy and never changes what the next handler sees.

LOGGING = {
    "version": 1,
    "formatters": {
        "safe": {
            "()": "bw_essentials.observability.logging.SafeFormatter",
            "format": "%(asctime)s %(levelname)s %(name)s %(message)s",
        },
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "formatter": "safe",
        },
        "file": {
            "class": "logging.handlers.RotatingFileHandler",
            "filename": "/var/log/application.log",
            "maxBytes": 10_000_000,
            "backupCount": 5,
            "formatter": "safe",
        },
    },
}

Use the same "formatter": "safe" setting on a CloudWatch handler. The supported startup order is configure_logging() first, init_otel() second, and configure_otel_logging() third. configure_logging() replaces root handlers, so add any service-owned extra sinks after that call.

Add the Django access logger after authentication/context middleware when tenant and broker fields should be present:

MIDDLEWARE = [
    # authentication and verified observability-context middleware,
    "bw_essentials.observability.django.middleware.AccessLogMiddleware",
]

It emits one bw_essentials.access INFO record per non-health request using the resolved route template, method, status, and latency only. It never reads query strings, headers, or bodies.

The same per-process lifecycle owns the metrics provider. It exports through the configured OTLP protocol (HTTP/protobuf by default) every 60 seconds; set the standard OTEL_METRIC_EXPORT_INTERVAL value in milliseconds to override that interval. Every collection includes the cumulative observable gauge bw.service.heartbeat=1, labelled with service.name, deployment.environment, and process.pid, even when the service is idle.

For the SigNoz telemetry-silence alert, use the PromQL query below and fire when the result is 1. The ten-minute range deliberately tolerates missed one-minute collections. SigNoz's Prometheus-compatible name translation changes dots to underscores in metric and attribute names:

absent_over_time(bw_service_heartbeat{service_name="VALUE_1",deployment_environment="VALUE_1"}[10m])

Observability CI tools

bw-obs-secret-grep <paths> recursively scans Python and JavaScript logging calls and exits 1 with deterministic file:line findings. A reviewed call can be exempted with # bw-obs: allow inside that call.

bw-obs-manifest-lint <yaml files> exits 1 when any Kubernetes Deployment or Rollout container omits OTEL_EXPORTER_OTLP_ENDPOINT or OTEL_SERVICE_NAME. An envFrom container is accepted only with an explicit BW_OBS_ALLOW_OTEL_ENV_FROM=true env value, or a pod-template/workload annotation bw-obs/allow-env-from: "true". YAML support is optional at runtime; install the tools extra to provide PyYAML.


Let me know if you'd like a logo badge, GitHub Actions setup, or example .whl build as well.

📬 Contact

For bugs or feature requests, open an issue or contact support+tech@investorai.in

Metadata

Release files for bw-essentials-core 0.2.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for bw-essentials-core 0.2.1
File Size Uploaded Provenance Actions
bw_essentials_core-0.2.1.tar.gz 239.2 kB Without provenance Details for bw_essentials_core-0.2.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for bw-essentials-core 0.2.1
File Interpreter ABI Platform Actions
bw_essentials_core-0.2.1-py3-none-any.whl Python 3 none any Details for bw_essentials_core-0.2.1-py3-none-any.whl

Total release size: 481.8 kB

Release files / bw_essentials_core-0.2.1.tar.gz

Download URL bw_essentials_core-0.2.1.tar.gz
Size 239.2 kB
Tags Source
SHA-256 checksum
How to use checksums
6b4608faab3e5325591bdcc712f2704a7e4bbfd615b71d7eda91b972a7d7b971
BLAKE2b-256 checksum
How to use checksums
69e226911faa30ccab8b7909cbbc44b4b7b7679629cffe4630c7edc9c3523ef4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.0

Release files / bw_essentials_core-0.2.1-py3-none-any.whl

Download URL bw_essentials_core-0.2.1-py3-none-any.whl
Size 242.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
dbc44d42659243e7d192ba2ed732ff76c6f7ae724ade709fbab85ce85e006d98
BLAKE2b-256 checksum
How to use checksums
e1c4be709ce884de7baaa2c5109bd7b2c437433e6e178dd8c9b0b65ebc5904da
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.0

Security for bw-essentials-core 0.2.1

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.

Release history Release notifications | RSS feed

This release

0.2.1 This release

2 release files No provenance

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