Skip to main content

TimescaleDB is a Python Client based on SQLModel and SQLAlchemy for high-performance real-time analytics time-series data.

Project description

TimescaleDB for Python

Python Client for TimescaleDB -- an open-source time-series database built on PostgreSQL. This package is based on SQLModel and SQLAlchemy and designed to be used with FastAPI, Flask, and more.

Looking for Django? Check out django-timescaledb

Installation

pip install timescaledb

Usage

Create a TimescaleDB Model

The TimescaleModel class inherits from SQLModel but incldues a time field for TimescaleDB hypertables and an id field for primary keys.

models.py

from sqlmodel import Field, SQLModel

from timescaledb import TimescaleModel

# create a model
class Metric(TimescaleModel, table=True):
    temp: float


class MetricCreate(Metric):
    # not a table but a Pydantic model
    temp: float


class MetricRead(Metric):
    # not a table but a Pydantic model
    id: int
    temp: float
    time: datetime = Field(default=None)

Initialize the Database

The timescaledb.create_engine is a wrapper around sqlmodel.create_engine (which is a wrapper around sqlalchemy.create_engine) that ensures a timezone is set for your database.

database.py

import timescaledb
from sqlmodel import Session, SQLModel

DATABASE_URL = "postgresql://user:password@localhost:5432/timescaledb"
TIME_ZONE = "UTC"
ECHO_QUERIES = False

engine = timescaledb.create_engine(DATABASE_URL, timezone=TIME_ZONE, echo=ECHO_QUERIES)


def get_session():
    with Session(engine) as session:
        yield session

def init_db():
    # Create all tables
    print("Creating database tables...")
    # automatically creates all tables that inherit from SQLModel
    SQLModel.metadata.create_all(engine)

    print("Creating hypertables...")
    # automatically creates hypertables for all models that inherit from TimescaleModel
    timescaledb.metadata.create_all(engine)

Create a FastAPI App

Put it all together in a FastAPI app.

main.py

from fastapi import FastAPI

from .database import init_db, get_session
from .models import Metric, MetricCreate, MetricRead

app = FastAPI()

@app.on_event("startup")
def on_startup():
    init_db()

@app.post("/metrics/", response_model=MetricRead)
def create_metric(metric: MetricCreate, session: Session = Depends(get_session)):
    db_metric = models.Metric.from_orm(metric)
    session.add(db_metric)
    session.commit()
    session.refresh(db_metric)
    return db_metric


@app.get("/metrics/{metric_id}", response_model=MetricRead)
def read_metric(metric_id: int, session: Session = Depends(get_session)):
    metric = session.get(Metric, metric_id)
    if not metric:
        raise HTTPException(status_code=404, message="Metric not found")
    return metric


@app.get("/metrics/", response_model=list[MetricRead])
def list_metrics(session: Session = Depends(get_session)):
    metrics = session.query(Metric).all()
    return metrics

Review the Sample Project

In ./sample_project you can review a complete example that includes:

  • A TimescaleDB model
  • A FastAPI app
  • Sample queries (time_bucket_gapfill_query, time_bucket_query)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

timescaledb-0.0.2.tar.gz (6.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

timescaledb-0.0.2-py3-none-any.whl (8.5 kB view details)

Uploaded Python 3

File details

Details for the file timescaledb-0.0.2.tar.gz.

File metadata

  • Download URL: timescaledb-0.0.2.tar.gz
  • Upload date:
  • Size: 6.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.8

File hashes

Hashes for timescaledb-0.0.2.tar.gz
Algorithm Hash digest
SHA256 38214c48933fd459aff95ae2038973adbf12404df23f7c928a947604978a93f9
MD5 b70bf5763f1a574c5e4016698922aba0
BLAKE2b-256 915436a9ac58d512f23d63ed1a05dbc682f42e51227acca417292767a5bedce7

See more details on using hashes here.

Provenance

The following attestation bundles were made for timescaledb-0.0.2.tar.gz:

Publisher: workflow.yaml on jmitchel3/timescaledb-python

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file timescaledb-0.0.2-py3-none-any.whl.

File metadata

  • Download URL: timescaledb-0.0.2-py3-none-any.whl
  • Upload date:
  • Size: 8.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.8

File hashes

Hashes for timescaledb-0.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 71089ad7f133db40bb6c96bbe04a2a8e8b8ee975106aeeea93e4d43d8b3ced5d
MD5 35b23ee94618817c80a2036ead540f6d
BLAKE2b-256 d1cdb03cd5042fab96945be79187b94aafd45b7f5e30558c4fd67e1c0136b0d4

See more details on using hashes here.

Provenance

The following attestation bundles were made for timescaledb-0.0.2-py3-none-any.whl:

Publisher: workflow.yaml on jmitchel3/timescaledb-python

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page