How to Download and Read Files From Blob Objects
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical back up.
Quickstart: Manage blobs with Python v12 SDK
In this quickstart, yous acquire to manage blobs by using Python. Blobs are objects that tin can hold large amounts of text or binary data, including images, documents, streaming media, and archive data. Y'all'll upload, download, and list blobs, and you'll create and delete containers.
More resources:
- API reference documentation
- Library source code
- Package (Python Package Index)
- Samples
Prerequisites
- An Azure account with an active subscription. Create an account for gratis.
- An Azure Storage account. Create a storage account.
- Python 2.7 or three.6+.
Setting upward
This department walks y'all through preparing a project to piece of work with the Azure Blob Storage client library v12 for Python.
Create the project
Create a Python application named blob-quickstart-v12.
-
In a console window (such every bit cmd, PowerShell, or Bash), create a new directory for the project.
mkdir blob-quickstart-v12
-
Switch to the newly created blob-quickstart-v12 directory.
cd hulk-quickstart-v12
-
In side the blob-quickstart-v12 directory, create some other directory called information. This directory is where the blob data files will be created and stored.
mkdir data
Install the parcel
While still in the awarding directory, install the Azure Blob Storage client library for Python package past using the pip install
command.
pip install azure-storage-hulk
This control installs the Azure Blob Storage customer library for Python packet and all the libraries on which information technology depends. In this example, that is but the Azure core library for Python.
Set upwardly the app framework
From the project directory:
-
Open a new text file in your code editor
-
Add together
import
statements -
Create the structure for the program, including basic exception treatment
Hither's the lawmaking:
import os, uuid from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient, __version__ endeavour: impress("Azure Blob Storage five" + __version__ + " - Python quickstart sample") # Quick start lawmaking goes here except Exception equally ex: print('Exception:') print(ex)
-
Salvage 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 asking to Azure Storage, information technology must exist authorized. To authorize a request, add together your storage account credentials to the application every bit a connexion string. To view your storage account credentials, follow these steps:
-
Sign in to the Azure portal.
-
Locate your storage account.
-
In the storage business relationship bill of fare pane, nether Security + networking, select Admission keys. Here, you tin view the account admission keys and the complete connection cord for each key.
-
In the Admission keys pane, select Show keys.
-
In the key1 section, locate the Connection string value. Select the Re-create to clipboard icon to copy the connection string. You lot'll add the connection string value to an environment variable in the next section.
Configure your storage connectedness string
After you copy the connection cord, write information technology to a new environs variable on the local machine running the awarding. To fix the environment variable, open a console window, and follow the instructions for your operating organisation. Replace <yourconnectionstring>
with your actual connection string.
- Windows
- Linux and macOS
setx AZURE_STORAGE_CONNECTION_STRING "<yourconnectionstring>"
After you add together the environment variable in Windows, you lot must kickoff a new instance of the control window.
Restart programs
After you add together the environment variable, restart whatsoever running programs that will need to read the environs variable. For instance, restart your development surround or editor before you continue.
Object model
Azure Hulk Storage is optimized for storing massive amounts of unstructured data. Unstructured data is data that doesn't adhere to a particular information model or definition, such as text or binary information. Blob storage offers three types of resources:
- The storage account
- A container in the storage account
- A hulk in the container
The post-obit diagram shows the human relationship between these resources.
Utilize the following Python classes to interact with these resources:
- BlobServiceClient: The
BlobServiceClient
class allows you to manipulate Azure Storage resource and blob containers. - ContainerClient: The
ContainerClient
class allows you to manipulate Azure Storage containers and their blobs. - BlobClient: The
BlobClient
form allows you to dispense Azure Storage blobs.
Code examples
These example code snippets testify yous how to do the post-obit tasks with the Azure Blob Storage client library for Python:
- Get the connectedness cord
- Create a container
- Upload blobs to a container
- List the blobs in a container
- Download blobs
- Delete a container
Get the connection string
The code below retrieves the storage account connection string from the surroundings variable created in the Configure your storage connection string department.
Add this code inside the try
block:
# Call up the connection string for use with the application. The storage # connection string is stored in an environment variable on the auto # running the application called AZURE_STORAGE_CONNECTION_STRING. If the environment variable is # created after the application is launched in a panel or with Visual Studio, # the shell or application needs to exist closed and reloaded to take the # environment variable into account. connect_str = os.getenv('AZURE_STORAGE_CONNECTION_STRING')
Create a container
Decide on a proper noun for the new container. The code beneath appends a UUID value to the container proper name to ensure that information technology'south unique.
Create an instance of the BlobServiceClient class past calling the from_connection_string method. And then, call the create_container method to actually create the container in your storage account.
Add this code to the cease of the try
block:
# Create the BlobServiceClient object which volition be used to create a container client blob_service_client = BlobServiceClient.from_connection_string(connect_str) # Create a unique proper 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:
- Creates a local directory to hold information files.
- Creates a text file in the local directory.
- Gets a reference to a BlobClient object past calling the get_blob_client method on the BlobServiceClient from the Create a container section.
- Uploads the local text file to the blob by calling the upload_blob method.
Add this code to the end of the try
block:
# Create a local directory to concur blob information local_path = "./data" bone.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 up(upload_file_path, 'west') file.write("Hello, Earth!") file.shut() # Create a hulk customer using the local file name as the proper name for the blob blob_client = blob_service_client.get_blob_client(container=container_name, blob=local_file_name) print("\nUploading to Azure Storage as blob:\n\t" + local_file_name) # Upload the created file with open(upload_file_path, "rb") as data: blob_client.upload_blob(data)
List the blobs in a container
List the blobs in the container by calling the list_blobs method. In this example, only one blob has been added to the container, so the list performance returns just that i 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: impress("\t" + blob.name)
Download blobs
Download the previously created blob by calling the download_blob method. The example code adds a suffix of "DOWNLOAD" to the file name so that you can see both files in local file arrangement.
Add this lawmaking to the end of the try
block:
# Download the blob to a local file # Add 'DOWNLOAD' before the .txt extension so you tin see both files in the data directory download_file_path = os.path.join(local_path, str.supersede(local_file_name ,'.txt', 'DOWNLOAD.txt')) print("\nDownloading hulk to \northward\t" + download_file_path) with open up(download_file_path, "wb") as download_file: download_file.write(blob_client.download_blob().readall())
Delete a container
The following lawmaking cleans upward the resources the app created by removing the entire container using the delete_container method. You can as well delete the local files, if you lot similar.
The app pauses for user input by calling input()
before it deletes the hulk, container, and local files. Verify that the resources were created correctly, before they're deleted.
Add this code to the end of the try
block:
# Clean up print("\nPress the Enter key to begin clean up") input() print("Deleting blob container...") container_client.delete_container() print("Deleting the local source and downloaded files...") os.remove(upload_file_path) bone.remove(download_file_path) os.rmdir(local_path) print("Done")
Run the code
This app creates a examination file in your local folder and uploads it to Azure Hulk Storage. The instance then lists the blobs in the container, and downloads the file with a new proper noun. You lot can compare the sometime and new files.
Navigate to the directory containing the hulk-quickstart-v12.py file, so execute the following python
control to run the app.
python hulk-quickstart-v12.py
The output of the app is like to the following instance:
Azure Blob Storage v12 - Python quickstart sample Uploading to Azure Storage as hulk: quickstartcf275796-2188-4057-b6fb-038352e35038.txt Listing blobs... quickstartcf275796-2188-4057-b6fb-038352e35038.txt Downloading blob to ./information/quickstartcf275796-2188-4057-b6fb-038352e35038DOWNLOAD.txt Press the Enter key to begin clean up Deleting blob container... Deleting the local source and downloaded files... Done
Before you begin the cleanup process, check your data binder for the ii files. You can open them and observe that they're identical.
Subsequently you've verified the files, printing the Enter key to delete the exam files and terminate the demo.
Next steps
In this quickstart, you learned how to upload, download, and list blobs using Python.
To come across Hulk storage sample apps, proceed to:
- To learn more, see the Azure Storage customer libraries for Python.
- For tutorials, samples, quickstarts, and other documentation, visit Azure for Python Developers.
Feedback
Source: https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-python
0 Response to "How to Download and Read Files From Blob Objects"
إرسال تعليق