Skip to content

Instantly share code, notes, and snippets.

@nelsondev19
Last active February 18, 2023 20:11
Show Gist options
  • Save nelsondev19/eade5071c80f659bfa7ce9a452345d85 to your computer and use it in GitHub Desktop.
Save nelsondev19/eade5071c80f659bfa7ce9a452345d85 to your computer and use it in GitHub Desktop.
The main methods to use with Azure Blob Storage and python
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)
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)
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)
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)
def create_container(container: str):
try:
blob_service_client.create_container(container)
print("success")
except Exception as e:
print(e.message)
def delete_container(container: str):
try:
blob_service_client.delete_container(container)
print("success")
except Exception as e:
print(e.message)
def get_containers():
try:
containers = blob_service_client.list_containers()
print([container.name for container in containers])
except Exception as e:
print(e.message)
@nelsondev19
Copy link
Author

nelsondev19 commented Jan 5, 2022

Dependencies

pip install azure-storage-blob

Connection String

Connection String Azure Blob Storage

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment