Skip to content

Commit d13e308

Browse files
committed
Update for Python SDK V2
1 parent 0385769 commit d13e308

File tree

2 files changed

+89
-47
lines changed

2 files changed

+89
-47
lines changed

articles/iot-hub/iot-hub-python-python-file-upload.md

Lines changed: 89 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ At the end of this tutorial you run the Python console app:
3636
3737
## Prerequisites
3838

39-
[!INCLUDE [iot-hub-include-python-installation-notes](../../includes/iot-hub-include-python-installation-notes.md)]
39+
[!INCLUDE [iot-hub-include-python-v2-installation-notes](../../includes/iot-hub-include-python-v2-installation-notes.md)]
4040

4141
* Make sure that port 8883 is open in your firewall. The device sample in this article uses MQTT protocol, which communicates over port 8883. This port may be blocked in some corporate and educational network environments. For more information and ways to work around this issue, see [Connecting to IoT Hub (MQTT)](iot-hub-mqtt-support.md#connecting-to-iot-hub).
4242

@@ -46,84 +46,126 @@ At the end of this tutorial you run the Python console app:
4646

4747
In this section, you create the device app to upload a file to IoT hub.
4848

49-
1. At your command prompt, run the following command to install the **azure-iothub-device-client** package:
49+
1. At your command prompt, run the following command to install the **azure-iot-device** package:
5050

5151
```cmd/sh
52-
pip install azure-iothub-device-client
52+
pip install azure-iot-device
5353
```
5454
55-
2. Using a text editor, create a test file that you will upload to blob storage.
55+
1. At your command prompt, run the following command to install the **azure.storage.blob** package.
5656
57-
> [!NOTE]
58-
> IoT Hub Python SDK currently only supports uploading character-based files such as **.txt** files.
57+
```cmd/sh
58+
pip install azure.storage.blob
59+
```
60+
61+
1. Create a test file that you will upload to blob storage.
5962
60-
3. Using a text editor, create a **FileUpload.py** file in your working folder.
63+
1. Using a text editor, create a **FileUpload.py** file in your working folder.
6164
62-
4. Add the following `import` statements and variables at the start of the **FileUpload.py** file.
65+
1. Add the following `import` statements and variables at the start of the **FileUpload.py** file.
6366
6467
```python
65-
import time
66-
import sys
67-
import iothub_client
6868
import os
69-
from iothub_client import IoTHubClient, IoTHubClientError, IoTHubTransportProvider, IoTHubClientResult, IoTHubError
69+
import asyncio
70+
from azure.iot.device.aio import IoTHubDeviceClient
71+
from azure.core.exceptions import AzureError
72+
from azure.storage.blob import BlobClient
7073
7174
CONNECTION_STRING = "[Device Connection String]"
72-
PROTOCOL = IoTHubTransportProvider.HTTP
73-
74-
PATHTOFILE = "[Full path to file]"
75-
FILENAME = "[File name for storage]"
75+
PATH_TO_FILE = r"[Full path to local file]"
7676
```
7777
78-
5. In your file, replace `[Device Connection String]` with the connection string of your IoT hub device. Replace `[Full path to file]` with the path to the test file that you created, or any file on your device that you want to upload. Replace `[File name for storage]` with the name that you want to give to your file after it's uploaded to blob storage.
78+
1. In your file, replace `[Device Connection String]` with the connection string of your IoT hub device. Replace `[Full path to file]` with the path to the test file that you created, or any file on your device that you want to upload.
7979
80-
6. Create a callback for the **upload_blob** function:
80+
1. Create a function to upload the file to blob storage:
8181
8282
```python
83-
def blob_upload_conf_callback(result, user_context):
84-
if str(result) == 'OK':
85-
print ( "...file uploaded successfully." )
86-
else:
87-
print ( "...file upload callback returned: " + str(result) )
83+
async def store_blob(blob_info, file_name):
84+
try:
85+
sas_url = "https://{}/{}/{}{}".format(
86+
blob_info["hostName"],
87+
blob_info["containerName"],
88+
blob_info["blobName"],
89+
blob_info["sasToken"]
90+
)
91+
92+
print("\nUploading file: {} to Azure Storage as blob: {} in container {}\n".format(file_name, blob_info["blobName"], blob_info["containerName"]))
93+
94+
# Upload the specified file
95+
with BlobClient.from_blob_url(sas_url) as blob_client:
96+
with open(file_name, "rb") as f:
97+
result = blob_client.upload_blob(f, overwrite=True)
98+
return (True, result)
99+
100+
except FileNotFoundError as ex:
101+
# catch file not found and add an HTTP status code to return in notification to IoT Hub
102+
ex.status_code = 404
103+
return (False, ex)
104+
105+
except AzureError as ex:
106+
# catch Azure errors that might result from the upload operation
107+
return (False, ex)
88108
```
89109
90-
7. Add the following code to connect the client and upload the file. Also include the `main` routine:
110+
1. Add the following code to connect the client and upload the file:
91111
92112
```python
93-
def iothub_file_upload_sample_run():
113+
async def main():
94114
try:
95115
print ( "IoT Hub file upload sample, press Ctrl-C to exit" )
96116
97-
client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
117+
conn_str = CONNECTION_STRING
118+
file_name = PATH_TO_FILE
119+
blob_name = os.path.basename(file_name)
98120
99-
f = open(PATHTOFILE, "r")
100-
content = f.read()
121+
device_client = IoTHubDeviceClient.create_from_connection_string(conn_str)
101122
102-
client.upload_blob_async(FILENAME, content, len(content), blob_upload_conf_callback, 0)
123+
# Connect the client
124+
await device_client.connect()
103125
104-
print ( "" )
105-
print ( "File upload initiated..." )
126+
# Get the storage info for the blob
127+
storage_info = await device_client.get_storage_info_for_blob(blob_name)
106128
107-
while True:
108-
time.sleep(30)
129+
# Upload to blob
130+
success, result = await store_blob(storage_info, file_name)
109131
110-
except IoTHubError as iothub_error:
111-
print ( "Unexpected error %s from IoTHub" % iothub_error )
112-
return
113-
except KeyboardInterrupt:
114-
print ( "IoTHubClient sample stopped" )
115-
except:
116-
print ( "generic error" )
132+
if success == True:
133+
print("Upload succeeded. Result is: \n")
134+
print(result)
135+
print()
117136
118-
if __name__ == '__main__':
119-
print ( "Simulating a file upload using the Azure IoT Hub Device SDK for Python" )
120-
print ( " Protocol %s" % PROTOCOL )
121-
print ( " Connection string=%s" % CONNECTION_STRING )
137+
await device_client.notify_blob_upload_status(
138+
storage_info["correlationId"], True, 200, "OK: {}".format(file_name)
139+
)
140+
141+
else :
142+
# If the upload was not successful, the result is the exception object
143+
print("Upload failed. Exception is: \n")
144+
print(result)
145+
print()
146+
147+
await device_client.notify_blob_upload_status(
148+
storage_info["correlationId"], False, result.status_code, str(result)
149+
)
150+
151+
# Finally, disconnect the client
152+
await device_client.disconnect()
153+
154+
except Exception as ex:
155+
print("\nException:")
156+
print(ex)
157+
158+
except KeyboardInterrupt:
159+
print ( "\nIoTHubDeviceClient sample stopped" )
122160
123-
iothub_file_upload_sample_run()
161+
if __name__ == "__main__":
162+
asyncio.run(main())
163+
#loop = asyncio.get_event_loop()
164+
#loop.run_until_complete(main())
165+
#loop.close()
124166
```
125167
126-
8. Save and close the **UploadFile.py** file.
168+
1. Save and close the **UploadFile.py** file.
127169
128170
## Run the application
129171
@@ -137,7 +179,7 @@ Now you are ready to run the application.
137179
138180
2. The following screenshot shows the output from the **FileUpload** app:
139181
140-
![Output from simulated-device app](./media/iot-hub-python-python-file-upload/1.png)
182+
![Output from simulated-device app](./media/iot-hub-python-python-file-upload/run-device-app.png)
141183
142184
3. You can use the portal to view the uploaded file in the storage container you configured:
143185
34.8 KB
Loading

0 commit comments

Comments
 (0)