|
| 1 | +"""Cognos Report Data Ingestion Component. |
| 2 | +
|
| 3 | +Run a Cognos report with output_format=CSV or JSON, parse the result set |
| 4 | +as a DataFrame. Useful for landing report data into a warehouse or |
| 5 | +chaining downstream Dagster transforms. |
| 6 | +""" |
| 7 | +import io |
| 8 | +from typing import Any, Dict, Optional |
| 9 | + |
| 10 | +import dagster as dg |
| 11 | +from pydantic import Field |
| 12 | + |
| 13 | + |
| 14 | +class CognosReportDataIngestionComponent(dg.Component, dg.Model, dg.Resolvable): |
| 15 | + """Materialize a Cognos report's output as a DataFrame. |
| 16 | +
|
| 17 | + Example: |
| 18 | +
|
| 19 | + ```yaml |
| 20 | + type: dagster_community_components.CognosReportDataIngestionComponent |
| 21 | + attributes: |
| 22 | + asset_key: monthly_pnl_report |
| 23 | + report_id: i8B1A56A56789ABCDEF01234567890AB |
| 24 | + output_format: CSV |
| 25 | + parameters: |
| 26 | + Month: "2026-07" |
| 27 | + resource_key: cognos_resource |
| 28 | + ``` |
| 29 | + """ |
| 30 | + |
| 31 | + asset_key: str = Field(description="Asset key for the emitted DataFrame.") |
| 32 | + report_id: str = Field(description="Cognos report ID.") |
| 33 | + output_format: str = Field(default="CSV", description="CSV | JSON — parseable formats.") |
| 34 | + parameters: Optional[Dict[str, Any]] = Field(default=None) |
| 35 | + timeout_seconds: int = Field(default=600) |
| 36 | + group_name: Optional[str] = Field(default=None) |
| 37 | + resource_key: str = Field(default="cognos_resource") |
| 38 | + |
| 39 | + def build_defs(self, context: dg.ComponentLoadContext) -> dg.Definitions: |
| 40 | + _self = self |
| 41 | + required_resource_keys = {self.resource_key} |
| 42 | + |
| 43 | + @dg.asset( |
| 44 | + name=_self.asset_key, |
| 45 | + group_name=_self.group_name, |
| 46 | + required_resource_keys=required_resource_keys, |
| 47 | + compute_kind="cognos", |
| 48 | + ) |
| 49 | + def _the_asset(context: dg.AssetExecutionContext): |
| 50 | + try: |
| 51 | + import pandas as pd |
| 52 | + import requests |
| 53 | + except ImportError as e: |
| 54 | + raise Exception("pandas or requests library not installed") from e |
| 55 | + |
| 56 | + resource = getattr(context.resources, _self.resource_key) |
| 57 | + session = requests.Session() |
| 58 | + session.verify = resource.verify_ssl |
| 59 | + headers = resource.get_auth_headers() |
| 60 | + |
| 61 | + login_body = resource.login_body() |
| 62 | + if login_body is not None: |
| 63 | + r = session.post(f"{resource.api_base}/session", json=login_body, timeout=30) |
| 64 | + if r.status_code >= 300: |
| 65 | + raise Exception(f"Cognos login failed: {r.status_code}") |
| 66 | + |
| 67 | + fmt = _self.output_format.upper() |
| 68 | + if fmt not in ("CSV", "JSON"): |
| 69 | + raise Exception(f"Only CSV or JSON output_format supported for ingestion; got {fmt}") |
| 70 | + |
| 71 | + body: dict = {"format": fmt} |
| 72 | + if _self.parameters: |
| 73 | + body["parameters"] = [{"name": k, "value": str(v)} for k, v in _self.parameters.items()] |
| 74 | + |
| 75 | + run_url = f"{resource.report_url(_self.report_id)}/data" |
| 76 | + r = session.post(run_url, json=body, headers=headers, timeout=_self.timeout_seconds) |
| 77 | + if r.status_code >= 400: |
| 78 | + raise Exception(f"Cognos report run failed: {r.status_code} {r.text[:200]}") |
| 79 | + |
| 80 | + if fmt == "CSV": |
| 81 | + df = pd.read_csv(io.StringIO(r.text)) |
| 82 | + else: # JSON |
| 83 | + payload = r.json() or {} |
| 84 | + rows = payload.get("data") or payload.get("rows") or payload |
| 85 | + if isinstance(rows, dict): |
| 86 | + # Nested — walk one level to find a list. |
| 87 | + for v in rows.values(): |
| 88 | + if isinstance(v, list): |
| 89 | + rows = v |
| 90 | + break |
| 91 | + df = pd.DataFrame(rows if isinstance(rows, list) else []) |
| 92 | + |
| 93 | + context.add_output_metadata({ |
| 94 | + "row_count": len(df), |
| 95 | + "report_id": _self.report_id, |
| 96 | + "output_format": fmt, |
| 97 | + }) |
| 98 | + return df |
| 99 | + |
| 100 | + return dg.Definitions(assets=[_the_asset]) |
0 commit comments