|
| 1 | +"""The Intro Pipeline Template contains the example from the docs intro page""" |
| 2 | +import os |
| 3 | +from typing import Optional |
| 4 | +import pandas as pd |
| 5 | +import sqlalchemy as sa |
| 6 | + |
| 7 | +import dlt |
| 8 | +from dlt.sources.helpers import requests |
| 9 | + |
| 10 | + |
| 11 | +CRATEDB_ADDRESS = os.getenv("CRATEDB_ADDRESS", "postgresql://crate:@localhost:5432/") |
| 12 | + |
| 13 | + |
| 14 | +def load_api_data() -> None: |
| 15 | + """Load data from the chess api, for more complex examples use our rest_api source""" |
| 16 | + |
| 17 | + # Create a dlt pipeline that will load |
| 18 | + # chess player data to the CrateDB destination |
| 19 | + pipeline = dlt.pipeline( |
| 20 | + pipeline_name="from_api", |
| 21 | + destination=dlt.destinations.cratedb(CRATEDB_ADDRESS), |
| 22 | + dataset_name="doc", |
| 23 | + ) |
| 24 | + |
| 25 | + # Grab some player data from Chess.com API |
| 26 | + data = [] |
| 27 | + for player in ["magnuscarlsen", "rpragchess"]: |
| 28 | + response = requests.get(f"https://api.chess.com/pub/player/{player}", timeout=30) |
| 29 | + response.raise_for_status() |
| 30 | + data.append(response.json()) |
| 31 | + |
| 32 | + # Extract, normalize, and load the data |
| 33 | + load_info = pipeline.run( |
| 34 | + data=data, |
| 35 | + table_name="chess_players", |
| 36 | + ) |
| 37 | + print(load_info) # noqa: T201 |
| 38 | + |
| 39 | + |
| 40 | +def load_pandas_data() -> None: |
| 41 | + """Load data from a public csv via pandas""" |
| 42 | + |
| 43 | + owid_disasters_csv = ( |
| 44 | + "https://raw.githubusercontent.com/owid/owid-datasets/master/datasets/" |
| 45 | + "Natural%20disasters%20from%201900%20to%202019%20-%20EMDAT%20(2020)/" |
| 46 | + "Natural%20disasters%20from%201900%20to%202019%20-%20EMDAT%20(2020).csv" |
| 47 | + ) |
| 48 | + df = pd.read_csv(owid_disasters_csv) |
| 49 | + |
| 50 | + pipeline = dlt.pipeline( |
| 51 | + pipeline_name="from_csv", |
| 52 | + destination=dlt.destinations.cratedb(CRATEDB_ADDRESS), |
| 53 | + dataset_name="doc", |
| 54 | + ) |
| 55 | + load_info = pipeline.run( |
| 56 | + data=df, |
| 57 | + table_name="natural_disasters", |
| 58 | + ) |
| 59 | + |
| 60 | + print(load_info) # noqa: T201 |
| 61 | + |
| 62 | + |
| 63 | +def load_sql_data() -> None: |
| 64 | + """Load data from a sql database with sqlalchemy, for more complex examples use our sql_database source""" |
| 65 | + |
| 66 | + # Use any SQL database supported by SQLAlchemy, below we use a public |
| 67 | + # MySQL instance to get data. |
| 68 | + # NOTE: you'll need to install pymysql with `pip install pymysql` |
| 69 | + # NOTE: loading data from public mysql instance may take several seconds |
| 70 | + # NOTE: this relies on external public database availability |
| 71 | + engine = sa.create_engine( |
| 72 | + "mysql+pymysql://[email protected]:4497/Rfam" |
| 73 | + ) |
| 74 | + |
| 75 | + with engine.connect() as conn: |
| 76 | + # Select genome table, stream data in batches of 100 elements |
| 77 | + query = "SELECT * FROM genome LIMIT 1000" |
| 78 | + rows = conn.execution_options(yield_per=100).exec_driver_sql(query) |
| 79 | + |
| 80 | + pipeline = dlt.pipeline( |
| 81 | + pipeline_name="from_database", |
| 82 | + destination=dlt.destinations.cratedb(CRATEDB_ADDRESS), |
| 83 | + dataset_name="doc", |
| 84 | + ) |
| 85 | + |
| 86 | + # Convert the rows into dictionaries on the fly with a map function |
| 87 | + load_info = pipeline.run( |
| 88 | + data=(dict(row._mapping) for row in rows), |
| 89 | + table_name="genome", |
| 90 | + ) |
| 91 | + |
| 92 | + print(load_info) # noqa: T201 |
| 93 | + |
| 94 | + |
| 95 | +@dlt.resource(write_disposition="replace") |
| 96 | +def github_api_resource(api_secret_key: Optional[str] = dlt.secrets.value): |
| 97 | + from dlt.sources.helpers.rest_client import paginate |
| 98 | + from dlt.sources.helpers.rest_client.auth import BearerTokenAuth |
| 99 | + from dlt.sources.helpers.rest_client.paginators import HeaderLinkPaginator |
| 100 | + |
| 101 | + url = "https://api.github.com/repos/dlt-hub/dlt/issues" |
| 102 | + |
| 103 | + # Github allows both authenticated and non-authenticated requests (with low rate limits) |
| 104 | + auth = BearerTokenAuth(api_secret_key) if api_secret_key else None |
| 105 | + for page in paginate( |
| 106 | + url, |
| 107 | + auth=auth, |
| 108 | + paginator=HeaderLinkPaginator(), |
| 109 | + params={"state": "open", "per_page": "100"}, |
| 110 | + ): |
| 111 | + yield page |
| 112 | + |
| 113 | + |
| 114 | +@dlt.source |
| 115 | +def github_api_source(api_secret_key: Optional[str] = dlt.secrets.value): |
| 116 | + return github_api_resource(api_secret_key=api_secret_key) |
| 117 | + |
| 118 | + |
| 119 | +def load_github_data() -> None: |
| 120 | + """Load GitHub issues data using the github_api_source.""" |
| 121 | + pipeline = dlt.pipeline( |
| 122 | + pipeline_name="github_api_pipeline", |
| 123 | + destination=dlt.destinations.cratedb(CRATEDB_ADDRESS), |
| 124 | + dataset_name="doc", |
| 125 | + ) |
| 126 | + load_info = pipeline.run( |
| 127 | + data=github_api_source(), |
| 128 | + table_name="github_api_data", |
| 129 | + ) |
| 130 | + print(load_info) # noqa: T201 |
| 131 | + |
| 132 | + |
| 133 | +def main(): |
| 134 | + functions = [ |
| 135 | + load_api_data, |
| 136 | + load_pandas_data, |
| 137 | + load_sql_data, |
| 138 | + load_github_data, |
| 139 | + ] |
| 140 | + for func in functions: |
| 141 | + try: |
| 142 | + func() |
| 143 | + except Exception as e: |
| 144 | + print(f"Error in {func.__name__}: {e}") # noqa: T201 |
| 145 | + |
| 146 | + |
| 147 | +if __name__ == "__main__": |
| 148 | + main() |
0 commit comments