{"slug":"azure-storage-blob-py","title":"azure-storage-blob-py","summary":"Azure Blob Storage SDK for Python. Use for uploading, downloading, listing blobs, managing containers, and blob lifecycle. Triggers: \"blob storage\", \"BlobServiceClient\", \"ContainerClient\", \"BlobClient\", \"upload blob\", \"download blob\".","platform":"GitHub Copilot","tags":[],"authorName":"Ciza","authorSlug":"ciza","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-08-12T21:05:10.094311Z","repo":{"url":"https://github.com/microsoft/skills","stars":3226,"forks":373,"license":"MIT","updatedAt":"2026-11-19T11:04:16Z"},"bodyHtml":"<hr>\n<h2>name: azure-storage-blob-py\ndescription: |\nAzure Blob Storage SDK for Python. Use for uploading, downloading, listing blobs, managing containers, and blob lifecycle.\nTriggers: \"blob storage\", \"BlobServiceClient\", \"ContainerClient\", \"BlobClient\", \"upload blob\", \"download blob\".\nlicense: MIT\nmetadata:\nauthor: Microsoft\nversion: \"1.0.0\"\npackage: azure-storage-blob</h2>\n<h1>Azure Blob Storage SDK for Python</h1>\n<p>Client library for Azure Blob Storage — object storage for unstructured data.</p>\n<h2>Installation</h2>\n<pre><code>pip install azure-storage-blob azure-identity\n</code></pre>\n<h2>Environment Variables</h2>\n<pre><code>AZURE_STORAGE_ACCOUNT_NAME=&lt;your-storage-account&gt;  # Required for all auth methods\n# Or use full URL\nAZURE_STORAGE_ACCOUNT_URL=https://&lt;account&gt;.blob.core.windows.net  # Alternative to account name\nAZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production\n</code></pre>\n<h2>Authentication &amp; Lifecycle</h2>\n<blockquote>\n<p><strong>\uD83D\uDD11 Two rules apply to every code sample below:</strong></p>\n<ol>\n<li><strong>Prefer <code>DefaultAzureCredential</code>.</strong> It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.\n<ul>\n<li>Local dev: <code>DefaultAzureCredential</code> works as-is.</li>\n<li>Production: set <code>AZURE_TOKEN_CREDENTIALS=prod</code> (or <code>AZURE_TOKEN_CREDENTIALS=&lt;specific_credential&gt;</code>) to constrain the credential chain to production-safe credentials.</li>\n</ul>\n</li>\n<li><strong>Wrap every client in a context manager</strong> so HTTP transports, sockets, and token caches are released deterministically:\n<ul>\n<li>Sync: <code>with &lt;Client&gt;(...) as client:</code></li>\n<li>Async: <code>async with &lt;Client&gt;(...) as client:</code> <strong>and</strong> <code>async with DefaultAzureCredential() as credential:</code> (from <code>azure.identity.aio</code>)</li>\n</ul>\n</li>\n</ol>\n<p>Snippets may abbreviate this setup, but production code should always follow both rules.</p>\n</blockquote>\n<pre><code>from azure.identity import DefaultAzureCredential, ManagedIdentityCredential\nfrom azure.storage.blob import BlobServiceClient\n\n# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=&lt;specific_credential&gt;\ncredential = DefaultAzureCredential(require_envvar=True)\n# Or use a specific credential directly in production:\n# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes\n# credential = ManagedIdentityCredential()\naccount_url = \"https://&lt;account&gt;.blob.core.windows.net\"\n\nwith BlobServiceClient(account_url, credential=credential) as blob_service_client:\n    # Use blob_service_client here (see following sections for operations)\n    ...\n</code></pre>\n<h2>Client Hierarchy</h2>\n<table>\n<thead>\n<tr>\n<th>Client</th>\n<th>Purpose</th>\n<th>Get From</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>BlobServiceClient</code></td>\n<td>Account-level operations</td>\n<td>Direct instantiation</td>\n</tr>\n<tr>\n<td><code>ContainerClient</code></td>\n<td>Container operations</td>\n<td><code>blob_service_client.get_container_client()</code></td>\n</tr>\n<tr>\n<td><code>BlobClient</code></td>\n<td>Single blob operations</td>\n<td><code>container_client.get_blob_client()</code></td>\n</tr>\n</tbody>\n</table>\n<h2>Core Workflow</h2>\n<h3>Create Container</h3>\n<pre><code>container_client = blob_service_client.get_container_client(\"mycontainer\")\ncontainer_client.create_container()\n</code></pre>\n<h3>Upload Blob</h3>\n<pre><code># From file path\nblob_client = blob_service_client.get_blob_client(\n    container=\"mycontainer\",\n    blob=\"sample.txt\"\n)\n\nwith open(\"./local-file.txt\", \"rb\") as data:\n    blob_client.upload_blob(data, overwrite=True)\n\n# From bytes/string\nblob_client.upload_blob(b\"Hello, World!\", overwrite=True)\n\n# From stream\nimport io\nstream = io.BytesIO(b\"Stream content\")\nblob_client.upload_blob(stream, overwrite=True)\n</code></pre>\n<h3>Download Blob</h3>\n<pre><code>blob_client = blob_service_client.get_blob_client(\n    container=\"mycontainer\",\n    blob=\"sample.txt\"\n)\n\n# To file\nwith open(\"./downloaded.txt\", \"wb\") as file:\n    download_stream = blob_client.download_blob()\n    file.write(download_stream.readall())\n\n# To memory\ndownload_stream = blob_client.download_blob()\ncontent = download_stream.readall()  # bytes\n\n# Read into existing buffer\nstream = io.BytesIO()\nnum_bytes = blob_client.download_blob().readinto(stream)\n</code></pre>\n<h3>List Blobs</h3>\n<pre><code>container_client = blob_service_client.get_container_client(\"mycontainer\")\n\n# List all blobs\nfor blob in container_client.list_blobs():\n    print(f\"{blob.name} - {blob.size} bytes\")\n\n# List with prefix (folder-like)\nfor blob in container_client.list_blobs(name_starts_with=\"logs/\"):\n    print(blob.name)\n\n# Walk blob hierarchy (virtual directories)\nfor item in container_client.walk_blobs(delimiter=\"/\"):\n    if item.get(\"prefix\"):\n        print(f\"Directory: {item['prefix']}\")\n    else:\n        print(f\"Blob: {item.name}\")\n</code></pre>\n<h3>Delete Blob</h3>\n<pre><code>blob_client.delete_blob()\n\n# Delete with snapshots\nblob_client.delete_blob(delete_snapshots=\"include\")\n</code></pre>\n<h2>Performance Tuning</h2>\n<pre><code># Configure chunk sizes for large uploads/downloads\nwith BlobClient(\n    account_url=account_url,\n    container_name=\"mycontainer\",\n    blob_name=\"large-file.zip\",\n    credential=credential,\n    max_block_size=4 * 1024 * 1024,  # 4 MiB blocks\n    max_single_put_size=64 * 1024 * 1024  # 64 MiB single upload limit\n) as blob_client:\n    # Parallel upload\n    blob_client.upload_blob(data, max_concurrency=4)\n\n    # Parallel download\n    download_stream = blob_client.download_blob(max_concurrency=4)\n</code></pre>\n<h2>SAS Tokens (User Delegation)</h2>\n<p>Generate SAS tokens with a <strong>user delegation key</strong> signed by Microsoft Entra ID — never with an account key. This keeps SAS issuance tied to Entra audit/rotation.</p>\n<pre><code>from datetime import datetime, timedelta, timezone\nfrom azure.identity import DefaultAzureCredential\nfrom azure.storage.blob import (\n    BlobServiceClient,\n    BlobSasPermissions,\n    generate_blob_sas,\n)\n\nnow = datetime.now(timezone.utc)\naccount_url = \"https://&lt;account&gt;.blob.core.windows.net\"\n\nwith BlobServiceClient(account_url, credential=DefaultAzureCredential()) as service:\n    # Get a user delegation key (valid up to 7 days). Caller needs the\n    # \"Storage Blob Delegator\" role on the storage account.\n    udk = service.get_user_delegation_key(\n        key_start_time=now,\n        key_expiry_time=now + timedelta(hours=1),\n    )\n\n    sas_token = generate_blob_sas(\n        account_name=\"&lt;account&gt;\",\n        container_name=\"mycontainer\",\n        blob_name=\"sample.txt\",\n        user_delegation_key=udk,\n        permission=BlobSasPermissions(read=True),\n        expiry=now + timedelta(hours=1),\n    )\n\nblob_url = f\"{account_url}/mycontainer/sample.txt?{sas_token}\"\n</code></pre>\n<h2>Blob Properties and Metadata</h2>\n<pre><code># Get properties\nproperties = blob_client.get_blob_properties()\nprint(f\"Size: {properties.size}\")\nprint(f\"Content-Type: {properties.content_settings.content_type}\")\nprint(f\"Last modified: {properties.last_modified}\")\n\n# Set metadata\nblob_client.set_blob_metadata(metadata={\"category\": \"logs\", \"year\": \"2024\"})\n\n# Set content type\nfrom azure.storage.blob import ContentSettings\nblob_client.set_http_headers(\n    content_settings=ContentSettings(content_type=\"application/json\")\n)\n</code></pre>\n<h2>Async Client</h2>\n<pre><code>from azure.identity.aio import DefaultAzureCredential\nfrom azure.storage.blob.aio import BlobServiceClient\n\nasync def upload_async():\n    async with DefaultAzureCredential() as credential:\n        async with BlobServiceClient(account_url, credential=credential) as client:\n            blob_client = client.get_blob_client(\"mycontainer\", \"sample.txt\")\n            \n            with open(\"./file.txt\", \"rb\") as data:\n                await blob_client.upload_blob(data, overwrite=True)\n\n# Download async\nasync def download_async():\n    async with BlobServiceClient(account_url, credential=credential) as client:\n        blob_client = client.get_blob_client(\"mycontainer\", \"sample.txt\")\n        \n        stream = await blob_client.download_blob()\n        data = await stream.readall()\n</code></pre>\n<h2>Best Practices</h2>\n<ol>\n<li><strong>Pick sync OR async and stay consistent.</strong> Do not mix <code>azure.storage.blob</code> sync clients with <code>azure.storage.blob.aio</code> async clients in the same call path. Choose one mode per module.</li>\n<li><strong>Always use context managers for clients and async credentials.</strong> Wrap every client in <code>with BlobServiceClient(...) as client:</code> (sync) or <code>async with BlobServiceClient(...) as client:</code> (async). For async <code>DefaultAzureCredential</code> from <code>azure.identity.aio</code>, also use <code>async with credential:</code> so tokens and transports are cleaned up.</li>\n<li><strong>Use <code>DefaultAzureCredential</code></strong> for code that runs locally (instead of connection strings). Use a specific token credential for code that runs in Azure.</li>\n<li><strong>Set <code>overwrite=True</code></strong> explicitly when re-uploading</li>\n<li><strong>Use <code>max_concurrency</code></strong> for large file transfers</li>\n<li><strong>Prefer <code>readinto()</code></strong> over <code>readall()</code> for memory efficiency</li>\n<li><strong>Use <code>walk_blobs()</code></strong> for hierarchical listing</li>\n<li><strong>Set appropriate content types</strong> for web-served blobs</li>\n</ol>\n<h2>Reference Files</h2>\n<table>\n<thead>\n<tr>\n<th>File</th>\n<th>Contents</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><a href=\"references/capabilities.md\">references/capabilities.md</a></td>\n<td>Capability index mapping hero flows and non-hero references.</td>\n</tr>\n<tr>\n<td><a href=\"references/non-hero-scenarios.md\">references/non-hero-scenarios.md</a></td>\n<td>Dedicated non-hero examples (metadata/properties and async patterns).</td>\n</tr>\n</tbody>\n</table>\n","files":[{"path":"references/capabilities.md","sizeBytes":1310,"isText":true},{"path":"references/non-hero-scenarios.md","sizeBytes":1621,"isText":true},{"path":"SKILL.md","sizeBytes":9154,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-08-12T21:50:26.901653Z","sha256":"6E4AC62F194F05C33B18D87E4A3694A1E046BA8854F5D13CE16D5E5269406CE9","sizeBytes":4795},"review":null,"source":{"repositoryUrl":"https://github.com/microsoft/skills","path":".github/plugins/azure-sdk-python/skills/azure-storage-blob-py","license":"MIT","commit":"b35d2c60fac796bfd2cfd14ad3f550c73e92d9bb","subtreeSha":"B4F87CB952EE624E34243F264505F19C1D8B8EA52B9C100360F1612973F74693","lastSyncedAt":"2026-11-19T20:53:05.968523Z"},"reviewedAt":"2026-08-12T21:53:41.638754Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/azure-storage-blob-py"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install microsoft-skills@llmmart"},{"target":"git","command":"git clone https://github.com/microsoft/skills.git"}]}