Quickstart: Manage blobs with Python v12 SDK

In this quickstart, you learn to manage blobs by using Python. Blobs are objects that can hold large amounts of text or binary data, including images, documents, streaming media, and archive data. You'll upload, download, and list blobs, and y'all'll create and delete containers.

More resources:

  • API reference documentation
  • Library source code
  • Package (Python Package Index)
  • Samples

Prerequisites

  • An Azure business relationship with an active subscription. Create an account for free.
  • An Azure Storage account. Create a storage business relationship.
  • Python 2.7 or 3.6+.

Setting upwards

This section walks you lot through preparing a projection to work with the Azure Blob Storage client library v12 for Python.

Create the project

Create a Python application named blob-quickstart-v12.

  1. In a console window (such every bit cmd, PowerShell, or Fustigate), create a new directory for the project.

                      mkdir blob-quickstart-v12                                  
  2. Switch to the newly created blob-quickstart-v12 directory.

                      cd blob-quickstart-v12                                  
  3. In side the blob-quickstart-v12 directory, create another directory called data. This directory is where the blob data files will exist created and stored.

                      mkdir data                                  

Install the package

While still in the application directory, install the Azure Blob Storage customer library for Python parcel by using the pip install command.

              pip install azure-storage-blob                          

This control installs the Azure Blob Storage client library for Python package and all the libraries on which it depends. In this instance, that is simply the Azure core library for Python.

Set up the app framework

From the project directory:

  1. Open a new text file in your lawmaking editor

  2. Add import statements

  3. Create the structure for the programme, including basic exception handling

    Hither's the lawmaking:

                      import bone, uuid from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient, __version__  try:     print("Azure Blob Storage v" + __version__ + " - Python quickstart sample")      # Quick start lawmaking goes hither  except Exception every bit ex:     impress('Exception:')     print(ex)                                  
  4. Save the new file as blob-quickstart-v12.py in the blob-quickstart-v12 directory.

Copy your credentials from the Azure portal

When the sample application makes a request to Azure Storage, information technology must be authorized. To authorize a asking, add together your storage business relationship credentials to the application as a connection string. To view your storage account credentials, follow these steps:

  1. Sign in to the Azure portal.

  2. Locate your storage business relationship.

  3. In the storage account card pane, under Security + networking, select Admission keys. Hither, y'all can view the account access keys and the complete connexion string for each key.

    Screenshot that shows where the access key settings are in the Azure portal

  4. In the Access keys pane, select Show keys.

  5. In the key1 section, locate the Connection string value. Select the Re-create to clipboard icon to re-create the connectedness string. Yous'll add the connection string value to an environment variable in the next section.

    Screenshot showing how to copy a connection string from the Azure portal

Configure your storage connection string

After yous copy the connection string, write information technology to a new surroundings variable on the local motorcar running the application. To set the surround variable, open up a console window, and follow the instructions for your operating system. Replace <yourconnectionstring> with your actual connection string.

  • Windows
  • Linux and macOS
                  setx AZURE_STORAGE_CONNECTION_STRING "<yourconnectionstring>"                                  

After you add the environment variable in Windows, you must start a new instance of the control window.

Restart programs

After you add the environment variable, restart whatsoever running programs that will need to read the surround variable. For example, restart your evolution surround or editor before y'all go on.

Object model

Azure Blob Storage is optimized for storing massive amounts of unstructured data. Unstructured data is data that doesn't attach to a particular data model or definition, such as text or binary data. Blob storage offers 3 types of resources:

  • The storage account
  • A container in the storage account
  • A blob in the container

The following diagram shows the relationship between these resources.

Diagram of Blob storage architecture

Use the post-obit Python classes to interact with these resources:

  • BlobServiceClient: The BlobServiceClient class allows yous to manipulate Azure Storage resource and hulk containers.
  • ContainerClient: The ContainerClient class allows you to manipulate Azure Storage containers and their blobs.
  • BlobClient: The BlobClient class allows you to manipulate Azure Storage blobs.

Lawmaking examples

These example code snippets prove you lot how to do the following tasks with the Azure Blob Storage client library for Python:

  • Get the connection cord
  • Create a container
  • Upload blobs to a container
  • List the blobs in a container
  • Download blobs
  • Delete a container

Get the connection cord

The lawmaking below retrieves the storage account connectedness cord from the surroundings variable created in the Configure your storage connection string section.

Add together this code inside the try block:

              # Retrieve the connection cord for use with the application. The storage # connection string is stored in an environs variable on the car # running the awarding chosen AZURE_STORAGE_CONNECTION_STRING. If the surroundings variable is # created afterward the application is launched in a panel or with Visual Studio, # the shell or application needs to be closed and reloaded to accept the # environment variable into account. connect_str = os.getenv('AZURE_STORAGE_CONNECTION_STRING')                          

Create a container

Decide on a name for the new container. The lawmaking beneath appends a UUID value to the container name to ensure that it'due south unique.

Create an instance of the BlobServiceClient grade past calling the from_connection_string method. Then, call the create_container method to actually create the container in your storage account.

Add together this code to the end of the try block:

              # Create the BlobServiceClient object which will exist used to create a container client blob_service_client = BlobServiceClient.from_connection_string(connect_str)  # Create a unique name for the container container_name = str(uuid.uuid4())  # Create the container container_client = blob_service_client.create_container(container_name)                          

Upload blobs to a container

The following code snippet:

  1. Creates a local directory to hold information files.
  2. Creates a text file in the local directory.
  3. Gets a reference to a BlobClient object by calling the get_blob_client method on the BlobServiceClient from the Create a container section.
  4. Uploads the local text file to the blob by calling the upload_blob method.

Add this lawmaking to the stop of the try cake:

              # Create a local directory to agree blob data local_path = "./data" os.mkdir(local_path)  # Create a file in the local data directory to upload and download local_file_name = str(uuid.uuid4()) + ".txt" upload_file_path = os.path.join(local_path, local_file_name)  # Write text to the file file = open(upload_file_path, 'w') file.write("How-do-you-do, World!") file.close()  # Create a blob client using the local file name as the name for the hulk blob_client = blob_service_client.get_blob_client(container=container_name, blob=local_file_name)  print("\nUploading to Azure Storage as hulk:\n\t" + local_file_name)  # Upload the created file with open(upload_file_path, "rb") as information:     blob_client.upload_blob(data)                          

List the blobs in a container

Listing the blobs in the container by calling the list_blobs method. In this case, only 1 blob has been added to the container, so the listing operation returns simply that ane blob.

Add this code to the end of the try block:

              print("\nListing blobs...")  # List the blobs in the container blob_list = container_client.list_blobs() for blob in blob_list:     print("\t" + blob.proper noun)                          

Download blobs

Download the previously created blob past calling the download_blob method. The example code adds a suffix of "DOWNLOAD" to the file name so that you can encounter both files in local file organization.

Add this code to the terminate of the endeavour block:

              # Download the blob to a local file # Add together 'DOWNLOAD' before the .txt extension so you lot can meet both files in the information directory download_file_path = os.path.join(local_path, str.supercede(local_file_name ,'.txt', 'DOWNLOAD.txt')) impress("\nDownloading blob to \n\t" + download_file_path)  with open(download_file_path, "wb") as download_file:     download_file.write(blob_client.download_blob().readall())                          

Delete a container

The following code cleans up the resources the app created past removing the entire container using the ​delete_container method. You can besides delete the local files, if you similar.

The app pauses for user input by calling input() earlier it deletes the blob, container, and local files. Verify that the resources were created correctly, before they're deleted.

Add this code to the end of the endeavour block:

              # Clean up print("\nPress the Enter key to begin clean upward") input()  impress("Deleting hulk container...") container_client.delete_container()  print("Deleting the local source and downloaded files...") bone.remove(upload_file_path) os.remove(download_file_path) os.rmdir(local_path)  print("Done")                          

Run the lawmaking

This app creates a test file in your local folder and uploads it to Azure Blob Storage. The example and so lists the blobs in the container, and downloads the file with a new name. You can compare the old and new files.

Navigate to the directory containing the blob-quickstart-v12.py file, then execute the following python command to run the app.

              python blob-quickstart-v12.py                          

The output of the app is similar to the following example:

              Azure Blob Storage v12 - Python quickstart sample  Uploading to Azure Storage equally hulk:         quickstartcf275796-2188-4057-b6fb-038352e35038.txt  Listing blobs...         quickstartcf275796-2188-4057-b6fb-038352e35038.txt  Downloading blob to         ./data/quickstartcf275796-2188-4057-b6fb-038352e35038DOWNLOAD.txt  Press the Enter fundamental to brainstorm make clean up  Deleting blob container... Deleting the local source and downloaded files... Done                          

Before you lot brainstorm the cleanup procedure, check your data folder for the ii files. You can open up them and observe that they're identical.

After you've verified the files, press the Enter key to delete the test files and finish the demo.

Next steps

In this quickstart, you learned how to upload, download, and list blobs using Python.

To see Blob storage sample apps, go on to:

  • To larn more, see the Azure Storage client libraries for Python.
  • For tutorials, samples, quickstarts, and other documentation, visit Azure for Python Developers.