File: storage_blob_async.py

package info (click to toggle)
python-azure 20201208%2Bgit-6
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 1,437,920 kB
  • sloc: python: 4,287,452; javascript: 269; makefile: 198; sh: 187; xml: 106
file content (61 lines) | stat: -rw-r--r-- 1,822 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import os
import uuid
from azure.storage.blob.aio import BlobClient
from azure.core import exceptions


class StorageBlobAsync:
    def __init__(self):
        id = uuid.uuid1()

        connectionString = os.environ["STORAGE_CONNECTION_STRING"]
        self.blob = BlobClient.from_connection_string(
            conn_str=connectionString,
            container_name="mycontainer",
            blob_name="pyTestBlob-" + id.hex + ".txt",
        )

    async def upload_blob(self):
        print("uploading blob...")
        self.data = "This is a sample data for Python Test"
        await self.blob.upload_blob(self.data)
        print("\tdone")

    async def download_blob(self):
        print("downloading blob...")
        with open("./downloadedBlob.txt", "wb") as my_blob:
            blob_data = await self.blob.download_blob()
            await blob_data.readinto(my_blob)

        print("\tdone")

    async def delete_blob(self):
        print("Cleaning up the resource...")
        await self.blob.delete_blob()
        print("\tdone")

    async def run(self):
        print("")
        print("------------------------")
        print("Storage - Blob")
        print("------------------------")
        print("1) Upload a Blob")
        print("2) Download a Blob")
        print("3) Delete that Blob (Clean up the resource)")
        print("")

        # Ensure that the blob does not exists before the tests
        try:
            await self.delete_blob()
        except exceptions.AzureError:
            pass

        try:
            await self.upload_blob()
            await self.download_blob()
        finally:
            await self.delete_blob()