YDB Python SDK

3.26.8 · active · verified Sun Mar 29

The YDB Python SDK is the officially supported Python client for YDB (Yandex Database), a distributed SQL database. It provides comprehensive functionality for table operations, query execution, transaction management, authentication, async operations, topic operations for streaming data, and integrations with SQLAlchemy and DB-API 2.0. The library is actively maintained with frequent minor and patch releases, currently at version 3.26.8.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the YDB driver and session pool, connecting to a YDB instance. It prioritizes authentication via an environment variable `YDB_TOKEN` for `AuthTokenCredentials`, falling back to `AnonymousCredentials` if not provided, suitable for local setups. Replace `YDB_ENDPOINT` and `YDB_DATABASE` with your YDB instance details.

import os
import ydb

# Configure connection details from environment variables for flexibility
ENDPOINT = os.environ.get('YDB_ENDPOINT', 'grpcs://localhost:2135') # e.g., 'grpcs://ydb.example.com:2135'
DATABASE = os.environ.get('YDB_DATABASE', '/local/database') # e.g., '/path/to/my/db'
AUTH_TOKEN = os.environ.get('YDB_TOKEN')

def main():
    driver_config = ydb.DriverConfig(ENDPOINT, DATABASE)

    # Use token authentication if YDB_TOKEN is set, otherwise anonymous
    if AUTH_TOKEN:
        driver_config.credentials = ydb.credentials.AuthTokenCredentials(AUTH_TOKEN)
    else:
        # For local YDB or scenarios requiring no explicit auth (e.g., metadata service)
        driver_config.credentials = ydb.credentials.AnonymousCredentials()

    with ydb.Driver(driver_config) as driver:
        driver.wait(timeout=5, fail_fast=True)
        print("YDB driver initialized successfully.")

        # Create a session pool
        with ydb.SessionPool(driver) as session_pool:
            def execute_query(session):
                try:
                    session.execute('SELECT 1 as my_column;')
                    print("Query executed successfully.")
                except Exception as e:
                    print(f"Error executing query: {e}")

            session_pool.retry_operation_sync(execute_query)

if __name__ == '__main__':
    main()

view raw JSON →