Backblaze B2 SDK
The `b2sdk` library provides a comprehensive Python SDK for interacting with Backblaze B2 Cloud Storage. It allows developers to manage buckets, upload and download files, handle file versions, and more. The current version is 2.10.4, with releases occurring regularly to add features, fix bugs, and maintain compatibility.
Warnings
- breaking Python 3.8 support was dropped in `b2sdk` v2.10.0. Projects using `b2sdk` must now run on Python 3.9 or newer.
- gotcha The recommended API version for `b2sdk` is `v3` since `v2.9.1`. Importing `B2Api` from `b2sdk` directly (i.e., `from b2sdk import B2Api`) will use the older `v2` API, which may lack new features or lead to future compatibility issues.
- gotcha If using `SqliteAccountInfo` for local credential caching, upgrading to `b2sdk` v2.10.3 from an older version might encounter backwards compatibility issues due to changes in the sqlite schema related to multi-bucket key support.
- gotcha A retry bug in `upload_unbound_stream()` for small-file uploads could cause a `ValueError: I/O operation on closed file` if a retryable upload error occurred.
- gotcha The `b2sdk` library adapted `authorize_account` and key management flows for multi-bucket keys in `v2.9.1`. If you manage application keys that are scoped to multiple buckets, older integrations might need review.
Install
-
pip install b2sdk
Imports
- B2Api
from b2sdk.v3 import B2Api
- SqliteAccountInfo
from b2sdk.v3.account_info.sqlite_account_info import SqliteAccountInfo
Quickstart
import os
from b2sdk.v3 import B2Api
from b2sdk.v3.account_info.sqlite_account_info import SqliteAccountInfo
# It's recommended to store credentials in environment variables
APPLICATION_KEY_ID = os.environ.get('B2_APPLICATION_KEY_ID', 'YOUR_KEY_ID')
APPLICATION_KEY = os.environ.get('B2_APPLICATION_KEY', 'YOUR_KEY')
if APPLICATION_KEY_ID == 'YOUR_KEY_ID' or APPLICATION_KEY == 'YOUR_KEY':
print("Please set B2_APPLICATION_KEY_ID and B2_APPLICATION_KEY environment variables.")
else:
try:
# Initialize account info storage (can be SqliteAccountInfo, InMemoryAccountInfo, etc.)
info = SqliteAccountInfo()
b2_api = B2Api(info)
# Authorize with Backblaze B2
b2_api.authorize_account(
realm='production', # Or 'test' for integration testing
application_key_id=APPLICATION_KEY_ID,
application_key=APPLICATION_KEY
)
print("Successfully authorized with Backblaze B2.")
# Example: List your buckets
print("\nListing buckets:")
buckets = b2_api.list_buckets()
if buckets:
for bucket in buckets:
print(f" - {bucket.name} (ID: {bucket.id_}, Type: {bucket.bucket_type})")
else:
print(" No buckets found.")
except Exception as e:
print(f"An error occurred: {e}")