Skip to content

Commit ba75662

Browse files
authored
Merge pull request #214628 from pauljewellmsft/pauljewell-python-quickstart
Update Python quickstart for passwordless auth
2 parents d08cf90 + 4a5d939 commit ba75662

File tree

2 files changed

+149
-43
lines changed

2 files changed

+149
-43
lines changed
41.3 KB
Loading
Lines changed: 149 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
---
2-
title: 'Quickstart: Azure Blob Storage library v12 - Python'
3-
description: In this quickstart, you learn how to use the Azure Blob Storage client library version 12 for Python to create a container and a blob in Blob (object) storage. Next, you learn how to download the blob to your local computer, and how to list all of the blobs in a container.
2+
title: 'Quickstart: Azure Blob Storage client library for Python'
3+
description: In this quickstart, you learn how to use the Azure Blob Storage client library for Python to create a container and a blob in Blob (object) storage. Next, you learn how to download the blob to your local computer, and how to list all of the blobs in a container.
44
author: pauljewellmsft
55
ms.author: pauljewell
6-
ms.date: 09/26/2022
6+
ms.date: 10/20/2022
77
ms.topic: quickstart
88
ms.service: storage
99
ms.subservice: blobs
@@ -13,56 +13,52 @@ ms.custom: devx-track-python, mode-api
1313

1414
# Quickstart: Azure Blob Storage client library for Python
1515

16-
Get started with the Azure Blob Storage client library for Python to manage blobs and containers. Follow steps to install the package and try out example code for basic tasks.
16+
Get started with the Azure Blob Storage client library for Python to manage blobs and containers. Follow steps to install the package and try out example code for basic tasks in an interactive console app.
1717

1818
[API reference documentation](/python/api/azure-storage-blob) | [Library source code](https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/storage/azure-storage-blob) | [Package (PyPi)](https://pypi.org/project/azure-storage-blob/) | [Samples](../common/storage-samples-python.md?toc=%2fazure%2fstorage%2fblobs%2ftoc.json#blob-samples)
1919

2020
## Prerequisites
2121

22-
- An Azure account with an active subscription - [create an account for free](https://azure.microsoft.com/free/?ref=microsoft.com&utm_source=microsoft.com&utm_medium=docs&utm_campaign=visualstudio).
23-
- An Azure Storage account - [create a storage account](../common/storage-account-create.md).
24-
- [Python](https://www.python.org/downloads/) 2.7 or 3.6+.
22+
- Azure account with an active subscription - [create an account for free](https://azure.microsoft.com/free/?ref=microsoft.com&utm_source=microsoft.com&utm_medium=docs&utm_campaign=visualstudio)
23+
- Azure Storage account - [create a storage account](../common/storage-account-create.md)
24+
- [Python](https://www.python.org/downloads/) 3.6+
2525

2626
## Setting up
2727

28-
This section walks you through preparing a project to work with the Azure Blob Storage client library v12 for Python.
28+
This section walks you through preparing a project to work with the Azure Blob Storage client library for Python.
2929

3030
### Create the project
3131

32-
Create a Python application named *blob-quickstart-v12*.
32+
Create a Python application named *blob-quickstart*.
3333

34-
1. In a console window (such as PowerShell, cmd, or bash), create a new directory for the project.
34+
1. In a console window (such as PowerShell or Bash), create a new directory for the project:
3535

3636
```console
37-
mkdir blob-quickstart-v12
37+
mkdir blob-quickstart
3838
```
3939

40-
1. Switch to the newly created *blob-quickstart-v12* directory.
40+
1. Switch to the newly created *blob-quickstart* directory:
4141

4242
```console
43-
cd blob-quickstart-v12
43+
cd blob-quickstart
4444
```
4545

46-
### Install the package
46+
### Install the packages
4747

48-
From the project directory, install the Azure Blob Storage client library for Python package by using the `pip install` command.
48+
From the project directory, install packages for the Azure Blob Storage and Azure Identity client libraries using the `pip install` command. The **azure-identity** package is needed for passwordless connections to Azure services.
4949

5050
```console
51-
pip install azure-storage-blob
51+
pip install azure-storage-blob azure-identity
5252
```
5353

54-
This command installs the Azure Blob Storage for Python package and libraries on which it depends. In this case, the only dependency is the Azure core library for Python.
55-
5654
### Set up the app framework
5755

5856
From the project directory, follow steps to create the basic structure of the app:
5957

60-
1. Open a new text file in your code editor
61-
1. Add `import` statements, create the structure for the program, and include basic exception handling, as shown below
62-
1. Save the new file as *blob-quickstart-v12.py* in the *blob-quickstart-v12* directory.
63-
:::code language="python" source="~/azure-storage-snippets/blobs/quickstarts/python/V12/app_framework.py":::
64-
65-
[!INCLUDE [storage-quickstart-credentials-include](../../../includes/storage-quickstart-credentials-include.md)]
58+
1. Open a new text file in your code editor.
59+
1. Add `import` statements, create the structure for the program, and include basic exception handling, as shown below.
60+
1. Save the new file as *blob-quickstart.py* in the *blob-quickstart* directory.
61+
:::code language="python" source="~/azure-storage-snippets/blobs/quickstarts/python/app-framework-qs.py":::
6662

6763
## Object model
6864

@@ -86,20 +82,130 @@ Use the following Python classes to interact with these resources:
8682

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

89-
- [Get the connection string](#get-the-connection-string-for-authentication)
85+
- [Authenticate the client](#authenticate-the-client)
9086
- [Create a container](#create-a-container)
9187
- [Upload blobs to a container](#upload-blobs-to-a-container)
9288
- [List the blobs in a container](#list-the-blobs-in-a-container)
9389
- [Download blobs](#download-blobs)
9490
- [Delete a container](#delete-a-container)
9591

96-
### Get the connection string for authentication
92+
### Authenticate the client
93+
94+
Application requests to Azure Blob Storage must be authorized. Using the `DefaultAzureCredential` class provided by the Azure Identity client library is the recommended approach for implementing passwordless connections to Azure services in your code, including Blob Storage.
95+
96+
You can also authorize requests to Azure Blob Storage by using the account access key. However, this approach should be used with caution. Developers must be diligent to never expose the access key in an unsecure location. Anyone who has the access key is able to authorize requests against the storage account, and effectively has access to all the data. `DefaultAzureCredential` offers improved management and security benefits over the account key to allow passwordless authentication. Both options are demonstrated in the following example.
97+
98+
### [Passwordless (Recommended)](#tab/managed-identity)
99+
100+
`DefaultAzureCredential` supports multiple authentication methods and determines which method should be used at runtime. This approach enables your app to use different authentication methods in different environments (local vs. production) without implementing environment-specific code.
101+
102+
The order and locations in which `DefaultAzureCredential` looks for credentials can be found in the [Azure Identity library overview](/python/api/overview/azure/identity-readme#defaultazurecredential).
103+
104+
For example, your app can authenticate using your Azure CLI sign-in credentials with when developing locally. Your app can then use a [managed identity](/azure/active-directory/managed-identities-azure-resources/overview) once it has been deployed to Azure. No code changes are required for this transition.
105+
106+
#### Assign roles to your Azure AD user account
107+
108+
[!INCLUDE [assign-roles](../../../includes/assign-roles.md)]
109+
110+
#### Sign in and connect your app code to Azure using DefaultAzureCredential
111+
112+
You can authorize access to data in your storage account using the following steps:
113+
114+
1. Make sure you're authenticated with the same Azure AD account you assigned the role to on your storage account. You can authenticate via the Azure CLI, Visual Studio Code, or Azure PowerShell.
115+
116+
#### [Azure CLI](#tab/sign-in-azure-cli)
117+
118+
Sign-in to Azure through the Azure CLI using the following command:
119+
120+
```azurecli
121+
az login
122+
```
123+
124+
#### [Visual Studio Code](#tab/sign-in-visual-studio-code)
125+
126+
You'll need to [install the Azure CLI](/cli/azure/install-azure-cli) to work with `DefaultAzureCredential` through Visual Studio Code.
127+
128+
On the main menu of Visual Studio Code, navigate to **Terminal > New Terminal**.
129+
130+
Sign-in to Azure through the Azure CLI using the following command:
131+
132+
```azurecli
133+
az login
134+
```
135+
136+
#### [PowerShell](#tab/sign-in-powershell)
137+
138+
Sign-in to Azure using PowerShell via the following command:
139+
140+
```azurepowershell
141+
Connect-AzAccount
142+
```
97143
98-
The code below retrieves the storage account connection string from the environment variable created in the [Configure your storage connection string](#configure-your-storage-connection-string) section.
144+
2. To use `DefaultAzureCredential`, make sure that the **azure-identity** package is [installed](#install-the-packages), and the class is imported:
145+
146+
```python
147+
from azure.identity import DefaultAzureCredential
148+
```
149+
150+
3. Add this code inside the `try` block. When the code runs on your local workstation, `DefaultAzureCredential` uses the developer credentials of the prioritized tool you're logged into to authenticate to Azure. Examples of these tools include Azure CLI or Visual Studio Code.
151+
152+
:::code language="python" source="~/azure-storage-snippets/blobs/quickstarts/python/blob-quickstart.py" id="Snippet_CreateServiceClientDAC":::
153+
154+
4. Make sure to update the storage account name in the URI of your `BlobServiceClient` object. The storage account name can be found on the overview page of the Azure portal.
155+
156+
:::image type="content" source="./media/storage-quickstart-blobs-python/storage-account-name.png" alt-text="A screenshot showing how to find the storage account name.":::
157+
158+
> [!NOTE]
159+
> When deployed to Azure, this same code can be used to authorize requests to Azure Storage from an application running in Azure. However, you'll need to enable managed identity on your app in Azure. Then configure your storage account to allow that managed identity to connect. For detailed instructions on configuring this connection between Azure services, see the [Auth from Azure-hosted apps](/dotnet/azure/sdk/authentication-azure-hosted-apps) tutorial.
160+
161+
### [Connection String](#tab/connection-string)
162+
163+
A connection string includes the storage account access key and uses it to authorize requests. Always be careful to never expose the keys in an unsecure location.
164+
165+
> [!NOTE]
166+
> If you plan to use connection strings, you'll need permissions for the following Azure RBAC action: [Microsoft.Storage/storageAccounts/listkeys/action](/azure/role-based-access-control/resource-provider-operations#microsoftstorage). The least privilege built-in role with permissions for this action is [Storage Account Key Operator Service Role](/azure/role-based-access-control/built-in-roles#storage-account-key-operator-service-role), but any role which includes this action will work.
167+
168+
[!INCLUDE [retrieve credentials](../../../includes/retrieve-credentials.md)]
169+
170+
#### Configure your storage connection string
171+
172+
After you copy the connection string, write it to a new environment variable on the local machine running the application. To set the environment variable, open a console window, and follow the instructions for your operating system. Replace `<yourconnectionstring>` with your actual connection string.
173+
174+
**Windows**:
175+
176+
```cmd
177+
setx AZURE_STORAGE_CONNECTION_STRING "<yourconnectionstring>"
178+
```
179+
180+
After you add the environment variable in Windows, you must start a new instance of the command window.
181+
182+
**Linux**:
183+
184+
```bash
185+
export AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>"
186+
```
187+
188+
The code below retrieves the connection string for the storage account from the environment variable created earlier, and uses the connection string to construct a service client object.
99189

100190
Add this code inside the `try` block:
101191

102-
:::code language="python" source="~/azure-storage-snippets/blobs/quickstarts/python/V12/blob-quickstart-v12.py" id="Snippet_ConnectionString":::
192+
```python
193+
# Retrieve the connection string for use with the application. The storage
194+
# connection string is stored in an environment variable on the machine
195+
# running the application called AZURE_STORAGE_CONNECTION_STRING. If the environment variable is
196+
# created after the application is launched in a console or with Visual Studio,
197+
# the shell or application needs to be closed and reloaded to take the
198+
# environment variable into account.
199+
connect_str = os.getenv('AZURE_STORAGE_CONNECTION_STRING')
200+
201+
# Create the BlobServiceClient object
202+
blob_service_client = BlobServiceClient.from_connection_string(connect_str)
203+
```
204+
205+
> [!IMPORTANT]
206+
> The account access key should be used with caution. If your account access key is lost or accidentally placed in an insecure location, your service may become vulnerable. Anyone who has the access key is able to authorize requests against the storage account, and effectively has access to all the data. `DefaultAzureCredential` provides enhanced security features and benefits and is the recommended approach for managing authorization to Azure services.
207+
208+
---
103209

104210
### Create a container
105211

@@ -108,11 +214,11 @@ Decide on a name for the new container. The code below appends a UUID value to t
108214
> [!IMPORTANT]
109215
> Container names must be lowercase. For more information about naming containers and blobs, see [Naming and Referencing Containers, Blobs, and Metadata](/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata).
110216
111-
Create an instance of the [BlobServiceClient](/python/api/azure-storage-blob/azure.storage.blob.blobserviceclient) class by calling the [from_connection_string](/python/api/azure-storage-blob/azure.storage.blob.blobserviceclient#from-connection-string-conn-str--credential-none----kwargs-) method. Then, call the [create_container](/python/api/azure-storage-blob/azure.storage.blob.blobserviceclient#create-container-name--metadata-none--public-access-none----kwargs-) method to actually create the container in your storage account.
217+
Call the [create_container](/python/api/azure-storage-blob/azure.storage.blob.blobserviceclient#create-container-name--metadata-none--public-access-none----kwargs-) method to actually create the container in your storage account.
112218

113219
Add this code to the end of the `try` block:
114220

115-
:::code language="python" source="~/azure-storage-snippets/blobs/quickstarts/python/V12/blob-quickstart-v12.py" id="Snippet_CreateContainer":::
221+
:::code language="python" source="~/azure-storage-snippets/blobs/quickstarts/python/blob-quickstart.py" id="Snippet_CreateContainer":::
116222

117223
### Upload blobs to a container
118224

@@ -125,23 +231,23 @@ The following code snippet:
125231

126232
Add this code to the end of the `try` block:
127233

128-
:::code language="python" source="~/azure-storage-snippets/blobs/quickstarts/python/V12/blob-quickstart-v12.py" id="Snippet_UploadBlobs":::
234+
:::code language="python" source="~/azure-storage-snippets/blobs/quickstarts/python/blob-quickstart.py" id="Snippet_UploadBlobs":::
129235

130236
### List the blobs in a container
131237

132238
List the blobs in the container by calling the [list_blobs](/python/api/azure-storage-blob/azure.storage.blob.containerclient#list-blobs-name-starts-with-none--include-none----kwargs-) method. In this case, only one blob has been added to the container, so the listing operation returns just that one blob.
133239

134240
Add this code to the end of the `try` block:
135241

136-
:::code language="python" source="~/azure-storage-snippets/blobs/quickstarts/python/V12/blob-quickstart-v12.py" id="Snippet_ListBlobs":::
242+
:::code language="python" source="~/azure-storage-snippets/blobs/quickstarts/python/blob-quickstart.py" id="Snippet_ListBlobs":::
137243

138244
### Download blobs
139245

140246
Download the previously created blob by calling the [download_blob](/python/api/azure-storage-blob/azure.storage.blob.blobclient#download-blob-offset-none--length-none----kwargs-) method. The example code adds a suffix of "DOWNLOAD" to the file name so that you can see both files in local file system.
141247

142248
Add this code to the end of the `try` block:
143249

144-
:::code language="python" source="~/azure-storage-snippets/blobs/quickstarts/python/V12/blob-quickstart-v12.py" id="Snippet_DownloadBlobs":::
250+
:::code language="python" source="~/azure-storage-snippets/blobs/quickstarts/python/blob-quickstart.py" id="Snippet_DownloadBlobs":::
145251

146252
### Delete a container
147253

@@ -151,31 +257,31 @@ The app pauses for user input by calling `input()` before it deletes the blob, c
151257

152258
Add this code to the end of the `try` block:
153259

154-
:::code language="python" source="~/azure-storage-snippets/blobs/quickstarts/python/V12/blob-quickstart-v12.py" id="Snippet_CleanUp":::
260+
:::code language="python" source="~/azure-storage-snippets/blobs/quickstarts/python/blob-quickstart.py" id="Snippet_CleanUp":::
155261

156262
## Run the code
157263

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

160-
Navigate to the directory containing the *blob-quickstart-v12.py* file, then execute the following `python` command to run the app.
266+
Navigate to the directory containing the *blob-quickstart.py* file, then execute the following `python` command to run the app:
161267

162268
```console
163-
python blob-quickstart-v12.py
269+
python blob-quickstart.py
164270
```
165271

166-
The output of the app is similar to the following example:
272+
The output of the app is similar to the following example (UUID values omitted for readability):
167273

168274
```output
169-
Azure Blob Storage v12 - Python quickstart sample
275+
Azure Blob Storage Python quickstart sample
170276
171277
Uploading to Azure Storage as blob:
172-
quickstartcf275796-2188-4057-b6fb-038352e35038.txt
278+
quickstartUUID.txt
173279
174280
Listing blobs...
175-
quickstartcf275796-2188-4057-b6fb-038352e35038.txt
281+
quickstartUUID.txt
176282
177283
Downloading blob to
178-
./data/quickstartcf275796-2188-4057-b6fb-038352e35038DOWNLOAD.txt
284+
./data/quickstartUUIDDOWNLOAD.txt
179285
180286
Press the Enter key to begin clean up
181287
@@ -188,7 +294,7 @@ Before you begin the cleanup process, check your *data* folder for the two files
188294

189295
## Clean up resources
190296

191-
After you've verified the files and finished testing, press the **Enter** key to delete the test files along with the container you created in the storage account.
297+
After you've verified the files and finished testing, press the **Enter** key to delete the test files along with the container you created in the storage account. You can also use [Azure CLI](storage-quickstart-blobs-cli.md#clean-up-resources) to delete resources.
192298

193299
## Next steps
194300

@@ -197,7 +303,7 @@ In this quickstart, you learned how to upload, download, and list blobs using Py
197303
To see Blob storage sample apps, continue to:
198304

199305
> [!div class="nextstepaction"]
200-
> [Azure Blob Storage SDK v12 Python samples](https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/storage/azure-storage-blob/samples)
306+
> [Azure Blob Storage library for Python samples](https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/storage/azure-storage-blob/samples)
201307
202308
- To learn more, see the [Azure Storage client libraries for Python](/azure/developer/python/sdk/storage/overview).
203309
- For tutorials, samples, quickstarts, and other documentation, visit [Azure for Python Developers](/azure/python/).

0 commit comments

Comments
 (0)