How to use Azure Blob Storage with Python

Azure Blob Storage with Python
pip install azure-storage-blob

Blob Service Client

from os import getenv
from azure.storage.blob import BlobServiceClient

blob_service_client = BlobServiceClient.from_connection_string(
getenv("AZURE_STORAGE_CONNECTION_STRING"))

Methods for blobs (Files)

Upload Blob

def upload_blob(filename: str, container: str, data: BinaryIO):
try:
blob_client = blob_service_client.get_blob_client(
container=container, blob=filename)

blob_client.upload_blob(data)

print("success")
except Exception as e:
print(e.message)

Download Blob

def download_blob(filename: str, container: str):
try:
blob_client = blob_service_client.get_blob_client(
container=container, blob=filename)

print(blob_client.download_blob().readall())
except Exception as e:
print(e.message)

Delete Blob

def delete_blob(filename: str, container: str):
try:
blob_client = blob_service_client.get_blob_client(
container=container, blob=filename)
blob_client.delete_blob() print("success")
except Exception as e:
print(e.message)

Methods for Containers (Folders)

Create Container

def create_container(container: str):
try:
blob_service_client.create_container(container)
print("success")
except Exception as e:
print(e.message)

Delete Container

def delete_container(container: str):
try:
blob_service_client.delete_container(container)
print("success")
except Exception as e:
print(e.message)

List Containers

def get_containers():
try:
containers = blob_service_client.list_containers()
print([container.name for container in containers])
except Exception as e:
print(e.message)

Frontend Developer and Content Creator from El Salvador

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

CS371p Spring 2022: Christopher Carrasco — Week 2

The end of the Multidisciplinary Project Manager

6WIND vRouter Provisioning Guide for Bare Metal and VM Deployments

10 Tips To Write Cleaner Code.

The difference between Java and Golang in writing concurrent code to access shared variable

What is Coding — For Non-Technical people

The Opportunity Backlog Framework: A User-Focused Alternative To The Product Roadmap

How to Solve Super Egg Drop Problem with Dynamic Programming

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nelson Hernández

Nelson Hernández

Frontend Developer and Content Creator from El Salvador

More from Medium

Create Data frame using API

image.png

Python: Create Adjacency List (Graph) From CSV Columns

AI-OCR >> How to Extract Items From Invoices Using Azure Form Recognizer

Packaging & Tool Release