| title | Upload files from devices to Azure IoT Hub (Python) | ||||
|---|---|---|---|---|---|
| titleSuffix | Azure IoT Hub | ||||
| description | How to upload files from a device to the cloud using Azure IoT device SDK for Python. Uploaded files are stored in an Azure storage blob container. | ||||
| author | SoniaLopezBravo | ||||
| ms.author | sonialopez | ||||
| ms.service | azure-iot-hub | ||||
| ms.devlang | python | ||||
| ms.topic | include | ||||
| ms.date | 12/12/2024 | ||||
| ms.custom |
|
The azure-iot-device library must be installed before calling any related code.
pip install azure-iot-device
The azure.storage.blob package is used to perform the file upload.
pip install azure.storage.blob
This section describes how to upload a file from a device to an IoT hub using the IoTHubDeviceClient class from the Azure IoT SDK for Python.
import os
from azure.iot.device import IoTHubDeviceClient
from azure.core.exceptions import AzureError
from azure.storage.blob import BlobClientA device app can authenticate with IoT Hub using the following methods:
- X.509 certificate
- Shared access key
[!INCLUDE iot-hub-howto-auth-device-cert-python]
To connect a device to IoT Hub:
- Call create_from_connection_string to add the device primary connection string.
- Call connect to connect the device client.
For example:
# Add your IoT hub primary connection string
CONNECTION_STRING = "{Device primary connection string}"
device_client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
# Connect the client
device_client.connect()Call get_storage_info_for_blob to get information from an IoT hub about a linked Azure Storage account. This information includes the hostname, container name, blob name, and a SAS token. The get_storage_info_for_blob method also returns a correlation_id, which is used in the notify_blob_upload_status method. The correlation_id is IoT Hub's way of marking which Blob you're working on.
# Get the storage info for the blob
PATH_TO_FILE = "{Full path to local file}"
blob_name = os.path.basename(PATH_TO_FILE)
blob_info = device_client.get_storage_info_for_blob(blob_name)To upload a file into Blob Storage:
- Use from_blob_url to create a BlobClient object from a blob URL.
- Call upload_blob to upload the file into the Blob Storage.
This example parses the blob_info structure to create a URL that it uses to initialize an BlobClient. Then it calls upload_blob to upload the file into Blob Storage.
try:
sas_url = "https://{}/{}/{}{}".format(
blob_info["hostName"],
blob_info["containerName"],
blob_info["blobName"],
blob_info["sasToken"]
)
print("\nUploading file: {} to Azure Storage as blob: {} in container {}\n".format(file_name, blob_info["blobName"], blob_info["containerName"]))
# Upload the specified file
with BlobClient.from_blob_url(sas_url) as blob_client:
with open(file_name, "rb") as f:
result = blob_client.upload_blob(f, overwrite=True)
return (True, result)
except FileNotFoundError as ex:
# catch file not found and add an HTTP status code to return in notification to IoT hub
ex.status_code = 404
return (False, ex)
except AzureError as ex:
# catch Azure errors that might result from the upload operation
return (False, ex)Use notify_blob_upload_status to notify IoT hub of the status of the Blob Storage operation. Pass the correlation_id obtained by the get_storage_info_for_blob method. The correlation_id is used by IoT hub to notify any service that might be listening for a notification regarding the status of the file upload task.
This example notifies IoT hub of a successful file upload:
device_client.notify_blob_upload_status(storage_info["correlationId"], True, 200, "OK: {}".format(PATH_TO_FILE)Shut down the client. Once this method is called, any attempt at further client calls result in a ClientError being raised.
device_client.shutdown()The SDK includes two file upload samples: