YDB Python SDK
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
- breaking Starting with version 3.26.0, the YDB Python SDK dropped compatibility with Python 3.7. Users on Python 3.7 or older must upgrade to Python 3.8 or higher.
- gotcha Authentication is critical and has several methods. Older YDB Python SDK v2 documentation might refer to environment variables like `USE_METADATA_CREDENTIALS` or `SA_KEY_FILE` which are peculiar to deprecated versions. Always refer to the latest documentation for current authentication practices, which involve `ydb.credentials` classes.
- gotcha Errors like "Sent message larger than max" are now non-retryable starting from version 3.26.8. This change prevents indefinite retries on errors that cannot be resolved by retrying. [cite: Changelog]
- gotcha When using `ydb.dbapi` for DB-API 2.0 compliance, ensure you are importing `ydb.dbapi` from the main `ydb` SDK. While there's a separate `ydb-dbapi` package, the recommended approach for modern applications is to use the `ydb.dbapi` module directly provided by the `ydb` SDK.
Install
-
pip install ydb
Imports
- ydb
import ydb
- Driver
import ydb from ydb.driver import Driver
- SessionPool
from ydb.table import SessionPool
- dbapi
import ydb.dbapi
- iam
import ydb.iam
Quickstart
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()