> For the complete documentation index, see [llms.txt](https://docs.telemetry.sh/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.telemetry.sh/sdks/python.md).

# Python

### Installation

```sh
pip3 install telemetry-sh
```

### Usage

#### Import Library

```python
from telemetry_sh import Telemetry
from datetime import datetime, timezone
```

#### Initialize Client

```python
API_KEY = "YOUR_API_KEY"  # Replace with your actual API key
telemetry = Telemetry()
telemetry.init(API_KEY)
```

#### Log Some Data

Telemetry automatically creates tables when data is logged. In the following example, we log some Uber ride data to a table called `uber_rides`. Telemetry will automatically create this table and its corresponding schema with columns: `city`, `price`, and `timestamp`.

```python
data = {
    "city": "paris",
    "price": 42,
    "timestamp": datetime.now(timezone.utc).isoformat()
}

try:
    response = telemetry.log("uber_rides", data)
    print("Log response:", response)
except Exception as e:
    print("Error logging data:", e)
```

#### Query Some Data

You can query the data using SQL through the query API.

```python
query = """
    SELECT
        city,
        AVG(price) AS average_price
    FROM
        uber_rides
    GROUP BY
        city
"""

try:
    query_response = telemetry.query(query)
    print("Query response:", query_response)
except Exception as e:
    print("Error querying data:", e)
```

### Async Usage

In codebases that utilize `asyncio`, using synchronous requests to log data can block all ongoing asyncio tasks until the request completes. To address this, we've introduced `TelemetryAsync`, which leverages `aiohttp` internally to provide non-blocking, asynchronous logging.

**Installation**

Make sure you have the `telemetry-sh` package installed:

```bash
pip3 install telemetry-sh
```

**Import Library**

```python
from telemetry_sh import TelemetryAsync
from datetime import datetime, timezone
import asyncio
```

**Initialize Client**

```python
API_KEY = "YOUR_API_KEY"  # Replace with your actual API key
telemetry = TelemetryAsync()
await telemetry.init(API_KEY)
```

**Log Some Data Asynchronously**

`TelemetryAsync` allows you to log data without blocking other asyncio tasks. Telemetry automatically creates tables when data is logged. In the following example, we log some Uber ride data to a table called `uber_rides`. Telemetry will automatically create this table and its corresponding schema with columns: `city`, `price`, and `timestamp`.

```python
data = {
    "city": "paris",
    "price": 42,
    "timestamp": datetime.now(timezone.utc).isoformat()
}

async def log_data():
    try:
        response = await telemetry.log("uber_rides", data)
        print("Log response:", response)
    except Exception as e:
        print("Error logging data:", e)

# Run the async logging function
asyncio.run(log_data())
```

**Query Some Data Asynchronously**

Just like logging, querying data can also be performed asynchronously.

```python
query = """
    SELECT
        city,
        AVG(price) AS average_price
    FROM
        uber_rides
    GROUP BY
        city
"""

async def query_data():
    try:
        query_response = await telemetry.query(query)
        print("Query response:", query_response)
    except Exception as e:
        print("Error querying data:", e)

# Run the async query function
asyncio.run(query_data())
```

**Bulk Ingestion Support**

`TelemetryAsync` also supports bulk ingestion. The `log` method can accept a list of dictionaries in addition to a single dictionary.

```python
bulk_data = [
    {"city": "paris", "price": 42, "timestamp": datetime.now(timezone.utc).isoformat()},
    {"city": "london", "price": 50, "timestamp": datetime.now(timezone.utc).isoformat()},
]

async def log_bulk_data():
    try:
        response = await telemetry.log("uber_rides", bulk_data)
        print("Bulk log response:", response)
    except Exception as e:
        print("Error logging bulk data:", e)

# Run the async bulk logging function
asyncio.run(log_bulk_data())
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.telemetry.sh/sdks/python.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
