### Install b2sdk with pip Source: https://github.com/backblaze/b2-sdk-python/blob/master/README.md Use this command to install the SDK. Ensure you have pip installed. ```bash pip install b2sdk ``` -------------------------------- ### Install Development Tools Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/contributing.md Install the necessary development tools, `nox` and `uv`, using pip. These tools are essential for running development automation sessions. ```bash pip install nox uv ``` -------------------------------- ### Specify b2sdk version in requirements.txt Source: https://github.com/backblaze/b2-sdk-python/blob/master/README.md Pin the b2sdk version in your requirements.txt file to ensure compatibility. This example allows versions 2.x.x. ```text b2sdk>=2,<3 ``` -------------------------------- ### Initialize Synchronizer with Custom Options Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/api/sync.md Initializes the Synchronizer with specific configurations for file comparison, handling of newer files, and policies for managing older files. This example sets the comparison mode to SIZE, a threshold of 10 bytes, replaces newer files, and keeps deleted files for 10 days. ```python >>> from b2sdk.v3 import ScanPoliciesManager >>> from b2sdk.v3 import parse_folder >>> from b2sdk.v3 import Synchronizer, SyncReport >>> from b2sdk.v3 import KeepOrDeleteMode, CompareVersionMode, NewerFileSyncMode >>> import time >>> import sys >>> source = '/home/user1/b2_example' >>> destination = 'b2://example-mybucket-b2' >>> source = parse_folder(source, b2_api) >>> destination = parse_folder(destination, b2_api) >>> policies_manager = ScanPoliciesManager(exclude_all_symlinks=True) >>> synchronizer = Synchronizer( max_workers=10, policies_manager=policies_manager, dry_run=False, allow_empty_source=True, compare_version_mode=CompareVersionMode.SIZE, compare_threshold=10, newer_file_mode=NewerFileSyncMode.REPLACE, keep_days_or_delete=KeepOrDeleteMode.KEEP_BEFORE_DELETE, keep_days=10, ) ``` -------------------------------- ### Pinning Dependencies for Internal Interface Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/api_types.md When using the internal interface of b2sdk, it is recommended to pin your dependencies to a specific minor version to avoid breaking changes. This example shows how to add this to your requirements.txt file. ```text b2sdk>=4.5.6,<4.6.0 ``` -------------------------------- ### Load Bash Completions from a Directory Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/bash_completion.md This script iterates through a directory and sources any files found, enabling bash completion for tools installed in that directory. Ensure this is placed in your `~/.bash_completion` file. ```bash if [ -d "$HOME/.bash_completion.d" ]; then for file in "$HOME/.bash_completion.d/"* do source "$file" >/dev/null 2>&1 done fi ``` -------------------------------- ### Initialize Synchronizer with MODTIME Comparison and SKIP Mode Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/api/sync.md Configures the Synchronizer to compare files based on modification time (MODTIME) with a threshold of 10 seconds and to skip synchronization if the source file is newer than the destination. This setup is useful for avoiding unnecessary updates when only minor time differences exist or when explicit skipping is desired. ```python >>> synchronizer = Synchronizer( max_workers=10, policies_manager=policies_manager, dry_run=False, allow_empty_source=True, compare_version_mode=CompareVersionMode.MODTIME, compare_threshold=10, # in seconds newer_file_mode=NewerFileSyncMode.SKIP, ``` -------------------------------- ### Retrieve Bucket by Name Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/tutorial.md Get a Bucket object for an existing B2 bucket by providing its name. This allows for operations like listing files. ```python b2_api.get_bucket_by_name("example-mybucket-b2-1",) ``` -------------------------------- ### Perform Synchronization and Report Actions Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/api/sync.md Executes the synchronization process between source and destination folders using the configured Synchronizer. Reports actions like uploads and deletions to standard output. This example demonstrates the outcome when a file exists in the destination but not the source, leading to its deletion and hiding for 10 days. ```python >>> no_progress = False >>> with SyncReport(sys.stdout, no_progress) as reporter: synchronizer.sync_folders( source_folder=source, dest_folder=destination, now_millis=int(round(time.time() * 1000)), reporter=reporter, ) upload f1.txt delete hello.txt (old version) hide hello.txt ``` -------------------------------- ### Obtain Download Version Object by ID Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/quick_start.md Download a file by its ID and get the `DownloadVersion` object, which contains metadata about the downloaded file. ```python >>> file_id = '4_z5485a1682662eb3e60980d10_f113f963288e711a6_d20190404_m065910_c002_v0001095_t0044' >>> downloaded_file = b2_api.download_file_by_id(file_id) >>> download_version = downloaded_file.download_version ``` -------------------------------- ### Set Nox Python Versions Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/contributing.md Configure the Python versions used by `nox` sessions by setting the `NOX_PYTHONS` environment variable. This example sets sessions to run on Python 3.12 and 3.14. ```bash export NOX_PYTHONS=3.12,3.14 ``` -------------------------------- ### No Continuation - create_file Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/advanced.md Explicitly disables continuation for a file upload, forcing the SDK to start a new large file upload regardless of existing unfinished uploads. Manual or auto continuation can still be attempted in subsequent calls. ```python >>> bucket.create_file(input_sources, remote_name, file_info, auto_continue=False) ``` -------------------------------- ### Run Nox Format Session (Re-using Environment) Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/contributing.md Execute the `format` session with `nox`, demonstrating the re-use of an existing virtual environment for faster execution. ```bash $ nox -s format nox > Running session format nox > Re-using existing virtual environment at .nox/format. ... ``` -------------------------------- ### Build documentation with nox and watch for changes Source: https://github.com/backblaze/b2-sdk-python/blob/master/CONTRIBUTING.md Build the project documentation and automatically recompile when changes are detected in the source code or documentation files. ```bash nox -s doc ``` -------------------------------- ### Prepare B2 SDK Account Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/quick_start.md Initializes the B2 SDK with in-memory account information and authorizes the account using application key credentials. ```python >>> from b2sdk.v3 import * >>> info = InMemoryAccountInfo() >>> b2_api = B2Api(info, cache=AuthInfoCache(info)) >>> application_key_id = '4a5b6c7d8e9f' >>> application_key = '001b8e23c26ff6efb941e237deb182b9599a84bef7' >>> b2_api.authorize_account("production", application_key_id, application_key) ``` -------------------------------- ### Build Documentation and Watch for Changes Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/contributing.md Build the project documentation and enable watching for changes in both the documentation source and the project's source code. This is useful for iterative documentation development. ```bash $ nox -s doc ``` -------------------------------- ### Make Release Commit Source: https://github.com/backblaze/b2-sdk-python/blob/master/README.release.md Run this command to initiate the release commit process. Replace X.Y.Z with the target version number. ```bash nox -s make_release_commit -- X.Y.Z ``` -------------------------------- ### Get File Metadata Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/quick_start.md Retrieve metadata for a specific file version in B2 Cloud Storage using its file ID. The metadata includes details such as account ID, file ID, content length, SHA1 hash, content type, and server-side encryption information. ```python >>> file_id = '4_z5485a1682662eb3e60980d10_f113f963288e711a6_d20190404_m065910_c002_v0001095_t0044' >>> file_version = b2_api.get_file_info(file_id) >>> file_version.as_dict() {'accountId': '451862be08d0', 'action': 'upload', 'bucketId': '5485a1682662eb3e60980d10', 'contentLength': 1870579, 'contentSha1': 'd821849a70922e87c2b0786c0be7266b89d87df0', 'contentType': 'application/pdf', 'fileId': '4_z5485a1682662eb3e60980d10_f113f963288e711a6_d20190404_m065910_c002_v0001095_t0044', 'fileInfo': {'how': 'good-file', 'sse_c_key_id': 'user-generated-key-id'}, 'fileName': 'dummy_new.pdf', 'uploadTimestamp': 1554361150000, "serverSideEncryption": {"algorithm": "AES256", "mode": "SSE-C"}, } ``` -------------------------------- ### Run Nox Format Session Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/contributing.md Use `nox` to format the code. This command initiates the `format` session, which typically uses `ruff` for code formatting. ```bash $ nox -s format ``` -------------------------------- ### Configure PATH and Bash Completion Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/bash_completion.md Add this snippet to your `~/.bashrc` to ensure the `~/bin` directory is in your PATH before bash completion is loaded, and to enable bash completion features if not already enabled. ```bash if [ -d ~/bin ]; then PATH="$HOME/bin:$PATH" fi # enable programmable completion features (you don't need to enable # this, if it's already enabled in /etc/bash.bashrc and /etc/profile # sources /etc/bash.bashrc). if ! shopt -oq posix; then if [ -f /usr/share/bash-completion/bash_completion ]; then . /usr/share/bash-completion/bash_completion elif [ -f /etc/bash_completion ]; then . /etc/bash_completion fi fi ``` -------------------------------- ### Run Nox Format Session (Without Virtual Environment) Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/contributing.md Run the `format` session using `nox` without creating or re-using a virtual environment. This can be useful for specific CI or testing scenarios. ```bash $ nox --no-venv -s format nox > Running session format ... ``` -------------------------------- ### Run all linters with nox Source: https://github.com/backblaze/b2-sdk-python/blob/master/CONTRIBUTING.md Execute all configured linters for the project by running the 'lint' nox session. ```bash nox -s lint ``` -------------------------------- ### Build documentation non-interactively Source: https://github.com/backblaze/b2-sdk-python/blob/master/CONTRIBUTING.md Build the project documentation once without interactive prompts or watching for changes. ```bash nox --non-interactive -s doc ``` -------------------------------- ### Initialize InMemoryAccountInfo Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/tutorial.md Create an InMemoryAccountInfo object to store credentials, tokens, and cache in memory. This is the first step to using the b2sdk. ```python from b2sdk.v3 import InMemoryAccountInfo info = InMemoryAccountInfo() # store credentials, tokens and cache in memory ``` -------------------------------- ### Run All Tests Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/contributing.md Execute the test suite on all available Python versions by running the `test` session with `nox`. This ensures compatibility across different environments. ```bash $ nox -s test ``` -------------------------------- ### Build Documentation Non-interactively Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/contributing.md Build the project documentation in a non-interactive mode using `nox`. This command is suitable for automated build processes where user interaction is not possible. ```bash $ nox --non-interactive -s doc ``` -------------------------------- ### Prioritize Remote Sources for File Synthesis Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/advanced.md Setting `prioritize='remote'` instructs the planner to use remote sources whenever available, minimizing downloads. ```python >>> planner.create_file(input_sources, remote_name, file_info, prioritize='remote') # planner parts: cloud[A, D], local[D, E] ``` -------------------------------- ### Create a New Bucket Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/tutorial.md Create a new bucket in your B2 account. Bucket names must be unique across all B2 accounts. Specify 'allPublic' or 'allPrivate' for the bucket type. ```python bucket_name = 'example-mybucket-b2-1' bucket_type = 'allPublic' # or 'allPrivate' b2_api.create_bucket(bucket_name, bucket_type) ``` -------------------------------- ### Download File Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/quick_start.md Demonstrates how to download a file using a `FileVersion` object, which is equivalent to using the `download_file_by_id` method. ```APIDOC ## Download (only for `b2sdk.v3.FileVersion`) This method downloads the content of a file represented by a `FileVersion` object. ### Method ```python file_version.download() ``` ### Equivalent Operation ```python b2_api.download_file_by_id(file_version.id_) ``` ``` -------------------------------- ### Obtain File Version Objects by Listing Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/quick_start.md List files within a bucket, optionally filtering by prefix and retrieving only the latest versions. This yields `FileVersion` and folder name pairs. ```python >>> for file_version, folder_name in bucket.ls(latest_only=True, prefix='dir_name'): >>> ... ``` -------------------------------- ### Create a Bucket Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/quick_start.md Creates a new bucket with a specified name and type (e.g., 'allPublic' or 'allPrivate'). The bucket name must be unique across all B2 accounts. ```python >>> bucket_name = 'example-mybucket-b2-1' # must be unique in B2 (across all accounts!) >>> bucket_type = 'allPublic' # or 'allPrivate' >>> b2_api.create_bucket(bucket_name, bucket_type) Bucket<346501784642eb3e60980d10,example-mybucket-b2-1,allPublic> ``` -------------------------------- ### Synthesize File from Local and Remote Parts Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/advanced.md Use `create_file()` with an iterable of `WriteIntent` objects to combine data from remote parts and local files. This supports large output objects and can reduce data transfer. ```python >>> bucket = b2_api.get_bucket_by_name(bucket_name) >>> def generate_input(): ... yield WriteIntent( ... CopySource('4_z5485a1682662eb3e60980d10_f113f963288e711a6_d20190404_m065910_c002_v0001095_t0044', offset=0, length=lengthC), ... destination_offset=0, ... ) ... yield WriteIntent( ... UploadSourceLocalFile('my_local_path/to_file.txt'), # length = offsetF - offsetB ... destination_offset=offsetB, ... ) ... yield WriteIntent( ... CopySource('4_z5485a1682662eb3e60980d10_f113f963288e711a6_d20190404_m065910_c002_v0001095_t0044', offset=0, length=offsetG-offsetD), ... destination_offset=offsetD, ... ) ... >>> file_info = {'how': 'good-file'} >>> bucket.create_file(generate_input(), remote_name, file_info) ``` -------------------------------- ### Run all tests with nox Source: https://github.com/backblaze/b2-sdk-python/blob/master/CONTRIBUTING.md Execute the test suite across all available Python versions using the 'test' nox session. ```bash nox -s test ``` -------------------------------- ### Run nox format session Source: https://github.com/backblaze/b2-sdk-python/blob/master/CONTRIBUTING.md Use nox to format the code. This command runs the 'format' session provided by nox. ```bash nox -s format ``` -------------------------------- ### Prioritize Local Sources for File Synthesis Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/advanced.md When creating a file from multiple sources, setting `prioritize='local'` tells the planner to prefer local files over remote ones for overlapping ranges, minimizing uploads. ```python >>> bucket.create_file(input_sources, remote_name, file_info, prioritize='local') # planner parts: cloud[A, B], local[B, C], remote[C, D], local[D, E] ``` -------------------------------- ### Create a changelog entry Source: https://github.com/backblaze/b2-sdk-python/blob/master/CONTRIBUTING.md Use the 'towncrier create' command to generate a changelog file for a specific issue and type. ```bash towncrier create -c 'write your description here' 157.fixed.md ``` -------------------------------- ### Manual Continuation with Callback - create_file_stream Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/advanced.md Similar to create_file, use a callback to capture the large_file_id for manual continuation. This is specifically for the streamed version of create_file, supporting local sources only. ```python >>> def large_file_callback(large_file): ... # storage is not part of the interface - here only for demonstration purposes ... storage.store({'name': remote_name, 'large_file_id': large_file.id}) >>> bucket.create_file_stream(input_sources, remote_name, file_info, large_file_callback=large_file_callback) # ... >>> large_file_id = storage.query({'name': remote_name})[0]['large_file_id'] >>> bucket.create_file_stream(input_sources, remote_name, file_info, large_file_id=large_file_id) ``` -------------------------------- ### Copy File Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/quick_start.md Illustrates how to copy an existing file to a new location or with a new name within the bucket. It also covers copying parts of a file and handling large files. ```APIDOC ## Copy file This operation copies a file to a new name or location within the same bucket. It supports copying specific parts of a file and has considerations for large files. ### Method ```python new_file_version = bucket.copy(file_id, 'f2_copy.txt') bucket.copy(file_id, 'f2_copy.txt', offset=1024, length=2048) ``` ### Parameters - `file_id` (str): The ID of the source file to copy. - `new_file_name` (str): The name for the new copied file. - `offset` (int, optional): The starting byte offset for copying a portion of the file. - `length` (int, optional): The number of bytes to copy, starting from the offset. Required if `offset` is not zero. - `max_copy_part_size` (int, optional): The maximum size for copy parts, defaults to 5GB. ### Considerations - If `content_length` is not provided and the file is larger than 5GB, the copy operation may fail. - `max_copy_part_size` can be used to control how large files are copied. - SSE-C encrypted source files require the proper key to be provided. ``` -------------------------------- ### Obtain File Version Objects Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/quick_start.md Explains how to obtain `FileVersion` and `DownloadVersion` objects, which represent files and provide high-level access to file manipulation methods. ```APIDOC ## Obtain file representing objects These sections describe how to get `FileVersion` and `DownloadVersion` objects, which encapsulate file information and provide methods for interacting with files. ### `b2sdk.v3.FileVersion` #### By id Retrieves a `FileVersion` object using its unique file ID. ```python file_version = b2_api.get_file_info(file_id) ``` #### By listing Lists files within a bucket, optionally filtering by latest version and prefix, returning `FileVersion` objects. ```python for file_version, folder_name in bucket.ls(latest_only=True, prefix='dir_name'): ... ``` ### `b2sdk.v3.DownloadVersion` #### By id Downloads a file by its ID and returns a `DownloadVersion` object. ```python downloaded_file = b2_api.download_file_by_id(file_id) download_version = downloaded_file.download_version ``` #### By name Downloads a file by its name from a specified bucket and returns a `DownloadVersion` object. ```python downloaded_file = bucket.download_file_by_name(b2_file_name) download_version = downloaded_file.download_version ``` ``` -------------------------------- ### Run nox format session without virtual environment Source: https://github.com/backblaze/b2-sdk-python/blob/master/CONTRIBUTING.md Execute the 'format' nox session without creating or using a virtual environment. ```bash nox --no-venv -s format ``` -------------------------------- ### Initialize B2Api Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/tutorial.md Create a B2Api object using the AccountInfo object. This object is used for account-level operations. ```python from b2sdk.v3 import B2Api b2_api = B2Api(info) ``` -------------------------------- ### Run All Linters Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/contributing.md Execute all available linters by running the `lint` session with `nox`. This command helps identify potential issues with code maintainability. ```bash $ nox -s lint ``` -------------------------------- ### Initialize Synchronizer for Deletion Mode Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/api/sync.md Initializes the Synchronizer with `keep_days_or_delete=KeepOrDeleteMode.DELETE`. This configuration ensures that files deleted from the source are permanently removed from the destination without any retention period. ```python >>> synchronizer = Synchronizer( max_workers=10, policies_manager=policies_manager, dry_run=False, allow_empty_source=True, compare_version_mode=CompareVersionMode.SIZE, compare_threshold=10, # in bytes newer_file_mode=NewerFileSyncMode.REPLACE, keep_days_or_delete=KeepOrDeleteMode.DELETE, ) >>> with SyncReport(sys.stdout, no_progress) as reporter: synchronizer.sync_folders( source_folder=source, dest_folder=destination, now_millis=int(round(time.time() * 1000)), reporter=reporter, ) delete f1.txt delete f1.txt (old version) delete hello.txt (old version) upload f2.txt delete hello.txt (hide marker) ``` -------------------------------- ### Obtain Download Version Object by Name Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/quick_start.md Download a file by its name from a bucket and obtain its `DownloadVersion` object. Ensure the bucket object is retrieved first. ```python >>> bucket = b2_api.get_bucket_by_name(bucket_name) >>> b2_file_name = 'dummy_new.pdf' >>> downloaded_file = bucket.download_file_by_name(b2_file_name) >>> download_version = downloaded_file.download_version ``` -------------------------------- ### List Buckets Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/quick_start.md Retrieves and prints a list of all buckets associated with the authorized account, displaying their ID, type, and name. ```python >>> b2_api.list_buckets() [Bucket<346501784642eb3e60980d10,example-mybucket-b2-1,allPublic>] >>> for b in b2_api.list_buckets(): print('%s %-10s %s' % (b.id_, b.type_, b.name)) 346501784642eb3e60980d10 allPublic example-mybucket-b2-1 ``` -------------------------------- ### Public Interface Version Pinning Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/markup-test.rst If you only use public interfaces, pin your dependencies to a range that excludes the next major version. ```text >=4.5.6;<5.0.0 ``` -------------------------------- ### Run Tests on Specific Python Version Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/contributing.md Run the test suite on a specific Python version, such as 3.10, by using the `test-3.10` session with `nox`. ```bash $ nox -s test-3.10 ``` -------------------------------- ### Run tests on a specific Python version Source: https://github.com/backblaze/b2-sdk-python/blob/master/CONTRIBUTING.md Run the test suite on a particular Python version, e.g., Python 3.10, using the 'test-3.10' nox session. ```bash nox -s test-3.10 ``` -------------------------------- ### Prioritize Local Verification for File Synthesis Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/advanced.md Using `prioritize='local_verification'` splits remote ranges to allow for checksum verification against matching local ranges, ensuring data integrity. ```python >>> bucket.create_file(input_sources, remote_name, file_info) # or >>> bucket.create_file(input_sources, remote_name, file_info, prioritize='local_verification') # planner parts: cloud[A, B], cloud[B, C], cloud[C, D], local[D, E] ``` -------------------------------- ### Synchronization with Small File Changes Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/api/sync.md Runs synchronization when a file has been modified but the change is below the `compare_threshold`. With `compare_threshold=10` bytes, minor changes will not trigger a file replacement. ```python >>> with SyncReport(sys.stdout, no_progress) as reporter: synchronizer.sync_folders( source_folder=source, dest_folder=destination, now_millis=int(round(time.time() * 1000)), reporter=reporter, ) ``` -------------------------------- ### Implement Custom AccountInfo Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/api/account_info.md Inherit from UrlPoolAccountInfo to create a custom AccountInfo for server-side applications. This class provides groundwork for url pool functionality. ```python from b2sdk.v3 import UrlPoolAccountInfo class MyAccountInfo(UrlPoolAccountInfo): ... ``` -------------------------------- ### Auto Continuation - create_file Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/advanced.md Enables automatic continuation for large file uploads. The SDK attempts to find and resume an unfinished upload based on file name and size for local sources, or plan information for other cases. ```python >>> bucket.create_file(input_sources, remote_name, file_info) ``` -------------------------------- ### List Files in Bucket Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/quick_start.md List files within a B2 bucket. Supports listing only the latest version of files, recursive listing, and listing files within a specific folder. The output includes file name, upload timestamp, and folder name. ```python >>> bucket_name = 'example-mybucket-b2' >>> bucket = b2_api.get_bucket_by_name(bucket_name) >>> for file_version, folder_name in bucket.ls(latest_only=True): >>> print(file_version.file_name, file_version.upload_timestamp, folder_name) f2.txt 1560927489000 None som2.pdf 1554296578000 None some.pdf 1554296579000 None test-folder/.bzEmpty 1561005295000 test-folder/ # Recursive >>> bucket_name = 'example-mybucket-b2' >>> bucket = b2_api.get_bucket_by_name(bucket_name) >>> for file_version, folder_name in bucket.ls(latest_only=True, recursive=True): >>> print(file_version.file_name, file_version.upload_timestamp, folder_name) f2.txt 1560927489000 None som2.pdf 1554296578000 None some.pdf 1554296579000 None test-folder/.bzEmpty 1561005295000 test-folder/ test-folder/folder_file.txt 1561005349000 None # Within folder >>> bucket_name = 'example-mybucket-b2' >>> bucket = b2_api.get_bucket_by_name(bucket_name) >>> for file_version, folder_name in bucket.ls(folder_to_list='test-folder', latest_only=True): >>> print(file_version.file_name, file_version.upload_timestamp, folder_name) test-folder/.bzEmpty 1561005295000 None test-folder/folder_file.txt 1561005349000 None # list file versions >>> for file_version, folder_name in bucket.ls(latest_only=False): >>> print(file_version.file_name, file_version.upload_timestamp, folder_name) f2.txt 1560927489000 None f2.txt 1560849524000 None som2.pdf 1554296578000 None some.pdf 1554296579000 None ``` -------------------------------- ### Download File by Name Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/quick_start.md Download a file from B2 Cloud Storage by its name within a specified bucket. The downloaded content is then saved to a local file path. ```python >>> bucket = b2_api.get_bucket_by_name(bucket_name) >>> b2_file_name = 'dummy_new.pdf' >>> local_file_name = '/home/user1/b2_example/new3.pdf' >>> downloaded_file = bucket.download_file_by_name(b2_file_name) >>> downloaded_file.save_to(local_file_path) ``` -------------------------------- ### Manual Continuation with Callback - create_file Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/advanced.md Use a callback to store the large_file_id during the initial call, then pass it to a subsequent call to continue the upload. This is for the non-streamed version of create_file. ```python >>> def large_file_callback(large_file): ... # storage is not part of the interface - here only for demonstration purposes ... storage.store({'name': remote_name, 'large_file_id': large_file.id}) >>> bucket.create_file(input_sources, remote_name, file_info, large_file_callback=large_file_callback) # ... >>> large_file_id = storage.query({'name': remote_name})[0]['large_file_id'] >>> bucket.create_file(input_sources, remote_name, file_info, large_file_id=large_file_id) ``` -------------------------------- ### Private Interface Version Pinning Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/markup-test.rst If you use private interfaces, pin your dependencies strictly to the exact version to avoid breaking changes. ```text ==4.5.6 ``` -------------------------------- ### List, Filter, and Delete Files Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/quick_start.md Iterates through files in a bucket, applying conditional logic to delete old CSV files or download others. Requires `bucket` and `LegalHold` to be defined. ```python >>> for file_version, folder_name in bucket.ls(latest_only=True, prefix='dir_name'): >>> if file_version.mod_time_millis < 1627979193913 and file_version.file_name.endswith('.csv'): >>> if file_version.legal_hold.is_on(): >>> file_version = file_version.update_legal_hold(LegalHold.OFF) >>> file_version.delete() >>> else: >>> file_version.download().save_to(Path('/tmp/dir_name') / file_version.file_name) ``` -------------------------------- ### Run tests by keyword expression Source: https://github.com/backblaze/b2-sdk-python/blob/master/CONTRIBUTING.md Filter tests to run only those matching a specific keyword expression using the '-k' flag with a nox test session. ```bash nox -s unit-3.10 -- -k keyword ``` -------------------------------- ### Run Integration Tests on Specific Python Version Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/contributing.md Run integration tests on a specific Python version (e.g., 3.10) using `nox`. Requires setting `B2_TEST_APPLICATION_KEY` and `B2_TEST_APPLICATION_KEY_ID` environment variables. ```bash $ export B2_TEST_APPLICATION_KEY=your_app_key $ export B2_TEST_APPLICATION_KEY_ID=your_app_key_id $ nox -s integration-3.10 ``` -------------------------------- ### Protected Interface Version Pinning Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/markup-test.rst If you use public and protected interfaces, pin your dependencies to a more restrictive range, excluding the next minor version. ```text >=4.5.6;<4.6.0 ``` -------------------------------- ### Update File Legal Hold and Retention Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/quick_start.md Demonstrates how to update the legal hold and retention settings for a file version using both object-oriented and direct API calls. ```python >>> file_version.update_legal_hold(LegalHold.ON) >>> download_version.update_legal_hold(LegalHold.ON) >>> file_version.update_retention( FileRetentionSetting(RetentionMode.GOVERNANCE, int(time.time() + 100)*1000)) >>> download_version.update_retention( FileRetentionSetting(RetentionMode.GOVERNANCE, int(time.time() + 100)*1000)) >>> # equivalent to >>> b2_api.update_file_legal_hold(file_version.id_, file_version.file_name, LegalHold.ON) >>> b2_api.update_file_legal_hold(download_version.id_, download_version.file_name, LegalHold.ON) >>> b2_api.update_file_legal_hold( file_version.id_, file_version.file_name, FileRetentionSetting(RetentionMode.GOVERNANCE, int(time.time() + 100)*1000)) >>> b2_api.update_file_legal_hold( download_version.id_, download_version.file_name, FileRetentionSetting(RetentionMode.GOVERNANCE, int(time.time() + 100)*1000)) ``` -------------------------------- ### Synchronize Folders with DELETE Mode Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/api/sync.md This snippet demonstrates synchronizing folders using the `KeepOrDeleteMode.DELETE` option. It initializes a `Synchronizer` and then calls `sync_folders` within a `SyncReport` context. This configuration will delete files from the destination if they are older in the source. ```python >>> synchronizer = Synchronizer( max_workers=10, policies_manager=policies_manager, dry_run=False, allow_empty_source=True, compare_version_mode=CompareVersionMode.MODTIME, compare_threshold=10, keep_days_or_delete=KeepOrDeleteMode.DELETE, ) >>> with SyncReport(sys.stdout, no_progress) as reporter: synchronizer.sync_folders( source_folder=source, dest_folder=destination, now_millis=int(round(time.time() * 1000)), reporter=reporter, ) ``` -------------------------------- ### Synchronize Folders with REPLACE Mode Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/api/sync.md This snippet shows folder synchronization with `NewerFileSyncMode.REPLACE`. When a newer file is detected in the source, it will replace the older version in the destination. This is useful for ensuring the destination always has the latest version of files. ```python >>> synchronizer = Synchronizer( max_workers=10, policies_manager=policies_manager, dry_run=False, allow_empty_source=True, compare_version_mode=CompareVersionMode.MODTIME, compare_threshold=10, newer_file_mode=NewerFileSyncMode.REPLACE, keep_days_or_delete=KeepOrDeleteMode.DELETE, ) >>> with SyncReport(sys.stdout, no_progress) as reporter: synchronizer.sync_folders( source_folder=source, dest_folder=destination, now_millis=int(round(time.time() * 1000)), reporter=reporter, ) delete f2.txt (old version) upload f2.txt ``` -------------------------------- ### Run integration tests on a specific Python version Source: https://github.com/backblaze/b2-sdk-python/blob/master/CONTRIBUTING.md Execute integration tests for a specific Python version, e.g., Python 3.10. Ensure B2_TEST_APPLICATION_KEY and B2_TEST_APPLICATION_KEY_ID are set. ```bash export B2_TEST_APPLICATION_KEY=your_app_key export B2_TEST_APPLICATION_KEY_ID=your_app_key_id nox -s integration-3.10 ``` -------------------------------- ### Update File Lock Configuration Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/quick_start.md Demonstrates how to update the legal hold status and retention settings for a file. ```APIDOC ## Update file lock configuration This section shows how to update file lock configurations, including legal holds and retention settings. ### Method ```python b2_api.update_file_legal_hold(file_id, file_name, LegalHold.ON) b2_api.update_file_legal_hold( file_id, file_name, FileRetentionSetting(RetentionMode.GOVERNANCE, int(time.time() + 100)*1000)) ``` ### Parameters - `file_id` (str): The ID of the file to update. - `file_name` (str): The name of the file to update. - `legal_hold_status` (LegalHold): The desired legal hold status (e.g., `LegalHold.ON`). - `retention_setting` (FileRetentionSetting, optional): The retention settings for the file, including mode and duration. ``` -------------------------------- ### Synchronize Folders with Encryption Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/quick_start.md Synchronizes files between a local directory and a B2 bucket, supporting various encryption settings per bucket. Requires importing necessary modules and defining source/destination paths. ```python >>> from b2sdk.v3 import ScanPoliciesManager >>> from b2sdk.v3 import parse_folder >>> from b2sdk.v3 import Synchronizer >>> from b2sdk.v3 import SyncReport >>> import time >>> import sys >>> source = '/home/user1/b2_example' >>> destination = 'b2://example-mybucket-b2' >>> source = parse_folder(source, b2_api) >>> destination = parse_folder(destination, b2_api) >>> policies_manager = ScanPoliciesManager(exclude_all_symlinks=True) >>> synchronizer = Synchronizer( max_workers=10, policies_manager=policies_manager, dry_run=False, allow_empty_source=True, ) >>> no_progress = False >>> encryption_settings_provider = BasicSyncEncryptionSettingsProvider({ 'bucket1': EncryptionSettings(mode=EncryptionMode.SSE_B2), 'bucket2': EncryptionSettings( mode=EncryptionMode.SSE_C, key=EncryptionKey(secret=b'VkYp3s6v9y$B&E)H@McQfTjWmZq4t7w!', id='user-generated-key-id') ), 'bucket3': None, }) >>> with SyncReport(sys.stdout, no_progress) as reporter: synchronizer.sync_folders( source_folder=source, dest_folder=destination, now_millis=int(round(time.time() * 1000)), reporter=reporter, encryption_settings_provider=encryption_settings_provider, ) upload some.pdf upload som2.pdf ``` -------------------------------- ### Delete File using File Object Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/quick_start.md Shows how to delete a file using either a `FileVersion` or `DownloadVersion` object. ```APIDOC ## Delete Deletes a file using its object representation (`FileVersion` or `DownloadVersion`). ### Method ```python file_version.delete() download_version.delete() ``` ### Equivalent Operations ```python b2_api.delete_file_version(file_version.id_, file_version.file_name) b2_api.delete_file_version(download_version.id_, download_version.file_name) ``` ``` -------------------------------- ### Obtain File Version Object by ID Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/quick_start.md Retrieve file information using the file ID. This returns a `b2sdk.v3.FileVersion` object. ```python >>> file_id = '4_z5485a1682662eb3e60980d10_f113f963288e711a6_d20190404_m065910_c002_v0001095_t0044' >>> file_version = b2_api.get_file_info(file_id) ``` -------------------------------- ### Check for up-to-date uv lock file Source: https://github.com/backblaze/b2-sdk-python/blob/master/CONTRIBUTING.md Verify that the uv.lock file is synchronized with changes in pyproject.toml using 'uv lock --check'. ```bash uv lock --check ``` -------------------------------- ### Run Unit Tests on Specific Python Version Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/contributing.md Execute only the unit tests on a specific Python version, like 3.10, by invoking the `unit-3.10` session with `nox`. ```bash $ nox -s unit-3.10 ``` -------------------------------- ### Upload File Encrypted with SSE-C Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/quick_start.md Upload a local file to B2 Cloud Storage using Server-Side Encryption with Customer-Provided Keys (SSE-C). Ensure the EncryptionSetting is correctly configured with the secret key and key ID. ```python >>> local_file_path = '/home/user1/b2_example/new.pdf' >>> b2_file_name = 'dummy_new.pdf' >>> file_info = {'how': 'good-file'} >>> encryption_setting = EncryptionSetting( mode=EncryptionMode.SSE_C, key=EncryptionKey(secret=b'VkYp3s6v9y$B&E)H@McQfTjWmZq4t7w!', id='user-generated-key-id'), ) >>> bucket = b2_api.get_bucket_by_name(bucket_name) >>> bucket.upload_local_file( local_file=local_file_path, file_name=b2_file_name, file_infos=file_info, encryption=encryption_setting, ) ``` -------------------------------- ### Pinning b2sdk Dependency Version Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/api_types.md Use this format in requirements.txt to ensure compatibility with a specific major version of b2sdk, preventing breaking changes from future major releases. ```default b2sdk>=1.15.0,<2.0.0 ``` -------------------------------- ### Download File by ID and Manage Retention Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/quick_start.md Downloads a file using its ID, checks its content type, potentially updates retention settings, and then deletes the file. Requires `b2_api`, `Path`, `NO_RETENTION_FILE_SETTING` to be defined. ```python >>> file_id = '4_z5485a1682662eb3e60980d10_f113f963288e711a6_d20190404_m065910_c002_v0001095_t0044' >>> downloaded_file = b2_api.download_file_by_id(file_id) >>> download_version = downloaded_file.download_version >>> if download_version.content_type == 'video/mp4': >>> downloaded_file.save_to(Path('/tmp/dir_name') / download_version.file_name) >>> if download_version.file_retention != NO_RETENTION_FILE_SETTING: >>> download_version = download_version.update_retention( NO_RETENTION_FILE_SETTING, bypass_governance=True) >>> download_version.delete() ``` -------------------------------- ### Run unit tests on a specific Python version Source: https://github.com/backblaze/b2-sdk-python/blob/master/CONTRIBUTING.md Execute only the unit tests for a specific Python version, e.g., Python 3.10, using the 'unit-3.10' nox session. ```bash nox -s unit-3.10 ``` -------------------------------- ### Synchronization with Significant File Changes Source: https://github.com/backblaze/b2-sdk-python/blob/master/doc/source/api/sync.md Executes synchronization when a file has been modified by more than the `compare_threshold`. With `compare_threshold=10` bytes, significant changes will trigger a file replacement at the destination. ```python >>> with SyncReport(sys.stdout, no_progress) as reporter: synchronizer.sync_folders( source_folder=source, dest_folder=destination, now_millis=int(round(time.time() * 1000)), reporter=reporter, ) upload f1.txt ```