Upload Blobs with Python SDK
This guide demonstrates how to upload blobs to Azure Blob Storage using the Python SDK.
Prerequisites
- An Azure account with an active subscription.
- A storage account.
- Install the Azure Blob Storage client library for Python:
pip install azure-storage-blob
1. Connect to Your Storage Account
To interact with your storage account, you'll need your storage account name and key, or a connection string. The connection string is generally recommended as it contains all necessary information.
You can retrieve your storage account name and key from the Azure portal under your storage account's "Access keys" section. The connection string can also be found there.
2. Upload a Block Blob
The most common type of blob is a block blob. Here's how to upload a file as a block blob.
Example Code
This example uploads a local file named local_file.txt to a blob named remote_blob_name.txt in a container named my-container.
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient
import os
# Replace with your actual values
connection_string = "YOUR_AZURE_STORAGE_CONNECTION_STRING"
container_name = "my-container"
local_file_name = "local_file.txt"
blob_name = "remote_blob_name.txt"
def upload_blob(connection_string, container_name, local_file_name, blob_name):
try:
# Create the BlobServiceClient object
blob_service_client = BlobServiceClient.from_connection_string(connection_string)
# Get a client to interact with a specific blob
blob_client = blob_service_client.get_blob_client(container=container_name, blob=blob_name)
print(f"Uploading {local_file_name} to {blob_name} in container {container_name}...")
# Open the local file in binary read mode
with open(local_file_name, "rb") as data:
# Upload the blob
blob_client.upload_blob(data)
print("Upload successful!")
except Exception as ex:
print('Exception:')
print(ex)
if __name__ == "__main__":
# Create a dummy local file for demonstration if it doesn't exist
if not os.path.exists(local_file_name):
with open(local_file_name, "w") as f:
f.write("This is a sample file to upload.")
print(f"Created dummy file: {local_file_name}")
# Ensure the container exists (optional, but good practice)
try:
blob_service_client = BlobServiceClient.from_connection_string(connection_string)
blob_service_client.create_container(container_name)
print(f"Container '{container_name}' ensured.")
except Exception as e:
# Handle case where container already exists or other errors
print(f"Could not create container '{container_name}' (it might already exist): {e}")
upload_blob(connection_string, container_name, local_file_name, blob_name)
Important Notes:
- Replace
YOUR_AZURE_STORAGE_CONNECTION_STRINGwith your actual connection string. - Ensure the
local_file_nameexists in your local file system. - The
container_namemust exist in your storage account. The example code includes a step to create it if it doesn't exist, but it's good to manage containers explicitly. - The
blob_nameis the name the file will have in Azure Blob Storage.
3. Uploading Large Files
For very large files, consider using the parallel upload feature, which can significantly improve performance by uploading chunks of the file concurrently.
4. Other Blob Types
Azure Blob Storage also supports append blobs (for logging scenarios) and page blobs (for virtual machine disks). The SDK provides methods for these as well.
Uploading an Append Blob
# ... (previous setup) ...
def append_to_blob(connection_string, container_name, blob_name, data_to_append):
try:
blob_service_client = BlobServiceClient.from_connection_string(connection_string)
append_blob_client = blob_service_client.get_blob_client(container=container_name, blob=blob_name)
print(f"Appending data to {blob_name}...")
append_blob_client.append_blob(data_to_append)
print("Append successful!")
except Exception as ex:
print('Exception during append:')
print(ex)
# Example usage:
# append_to_blob(connection_string, container_name, "my_append_blob.log", "New log entry.\n")
Refer to the official Azure Blob Storage documentation for more advanced scenarios and detailed API information.