SQLAlchemy

Learn about importing the SQLAlchemy integration and how it captures queries from SQLAlchemy as breadcrumbs.

The SQLAlchemy integration captures queries from SQLAlchemy as breadcrumbs and spans.

Install sentry-sdk from PyPI with the sqlalchemy extra.

Copied
pip install --upgrade 'sentry-sdk[sqlalchemy]'

The SQLAlchemy integration is enabled automatically if you have the sqlalchemy package installed.

Copied
import sentry_sdk

sentry_sdk.init(
    dsn="https://examplePublicKey@o0.ingest.sentry.io/0
example-org / example-project
"
,
# Add data like request headers and IP for users, if applicable; # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info send_default_pii=True, # Set traces_sample_rate to 1.0 to capture 100% # of transactions for tracing. traces_sample_rate=1.0, # Set profiles_sample_rate to 1.0 to profile 100% # of sampled transactions. # We recommend adjusting this value in production. profiles_sample_rate=1.0, )

Copied
from sqlalchemy import create_engine
from sqlalchemy.sql import text

def main():
    sentry_sdk.init(...)  # same as above

    engine = create_engine(DATABASE_URL, echo=True)
    statement = text("SELECT 'Hello World'")

    with engine.connect() as conn:
        with sentry_sdk.start_transaction(name="testing_sentry"):
            result = conn.execute(statement)

main()

This will create a transaction called testing_sentry in the Performance section of sentry.io and will create a span for the SELECT statement.

It takes a couple of moments for the data to appear in sentry.io.

  • SQLAlchemy: 1.2+
  • Python: 3.6+
Was this helpful?
Help improve this content
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) or suggesting an update ("yeah, this would be better").