iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 9
0
Microsoft Azure

用Azure建立一條龍的服務系列 第 9

實戰!! - Storage

今天又要來講實戰性的內容了!將透過python程式碼實際執行storage相關功能。

Blob

首先來講我相對熟悉的Blob。在使用前須先安裝套件:

pip install azure-storage-blob

正式使用前,還需要準備blob的ConnectionString。在進入storage後,按一下settings中的Access keys,會看到裡面有key1 及 key2。每個key都有connection string,複製其中一個即可。我的做法是將connection string存在.env中,再用dotenv讀取,比較安全。

image-20200924230116922

以下程式碼為列出所有在tatamocontainer中的所有blob物件。

from dotenv import load_dotenv

load_dotenv()
connect_str = os.getenv('AZURE_STORAGE_CONNECTION_STRING')

# 建立 BlobServiceClient 物件
blob_service_client = BlobServiceClient.from_connection_string(connect_str)
# 設定已建立的container name
container_name = "tatamocontainer"
# 透過blob_service_client取得container client
container_client = blob_service_client.get_container_client(container_name)

print("\nListing blobs...")

# 將tatamocontainer中的blob都列出來
blob_list = container_client.list_blobs()
for blob in blob_list:
    print("\t" + blob.name)

會看到輸出結果如下:

Listing blobs...
	KaoDistrict.html

另外還有建立container、上傳blob、下載blob及刪除container等功能,可參考官方說明文件

Queue

使用前先安裝套件:

pip install azure-storage-queue

connection string與上一段說明取得的是同一個,可以直接使用。以下為設定取得taqueue連線,並傳送三筆訊息到queue中。

import os, uuid
from azure.storage.queue import QueueServiceClient, QueueClient, QueueMessage
from dotenv import load_dotenv

load_dotenv()
connect_str = os.getenv('AZURE_STORAGE_CONNECTION_STRING')

queue_name = 'taqueue'
# Instantiate a QueueClient which will be
# used to create and manipulate the queue
queue_client = QueueClient.from_connection_string(connect_str, queue_name)
print("\nAdding messages to the queue...")

# Send several messages to the queue
queue_client.send_message(u"First message")
queue_client.send_message(u"Second message")
# 也可以將訊息儲存,可調用資訊來更新訊息
saved_message = queue_client.send_message(u"Third message")

可看到azure上存放了這三筆訊息

image-20200924233607279

接著執行取得訊息的程式,這邊的取得方式有兩種,一個是現在用的peek(窺視),另一個是receive(接收)。peek只會收到訊息內容,而receive則包含其他詳細資訊。

print("\nPeek at the messages in the queue...")

# Peek at messages in the queue
peeked_messages = queue_client.peek_messages(max_messages=5)

for peeked_message in peeked_messages:
    # Display the message
    print("Message: " + peeked_message.content)

取得結果如下:

Peek at the messages in the queue...
Message: First message
Message: Second message
Message: Third message

接收訊息程式碼如下

print("\nReceiving messages from the queue...")

# Get messages from the queue
messages = queue_client.receive_messages(messages_per_page=5)
for message in messages:
    # Display the message
    print("Message: " + message)

接著會輸出詳細的訊息及相關資訊,且接收後訊息會消失,等同於之前service bus中執行complete()。

以上queue作法與情報員上戰場 - ServiceBus實作差不多,若有使用過servicebus的話還滿容易上手的。

Table

先安裝套件

pip install azure-cosmosdb-table

下方建立table_service 連線,並以dict型態建立task,然後透過table_service傳送至tatable中。

from azure.cosmosdb.table.tableservice import TableService
from azure.cosmosdb.table.models import Entity

from dotenv import load_dotenv

load_dotenv()
connect_str = os.getenv('AZURE_STORAGE_CONNECTION_STRING')
table_service = TableService(connection_string=connect_str)

# 建立並以dict型態至table
task = {'PartitionKey': 'tasksSeattle', 'RowKey': '001',
        'description': 'Take out the trash', 'priority': 200}
table_service.insert_entity('tatable', task)

另外也可以以物件的型態傳送

# 建立並以物件型態至table
task = Entity()
task.PartitionKey = 'tasksSeattle'
task.RowKey = '002'
task.description = 'Wash the car'
task.priority = 100
table_service.insert_entity('tatable', task)

兩種型態傳送到Azure Storage Table,都會各自存成一筆資料,讀取資料的程式碼與結果如下:

tasks = table_service.query_entities(
    'tatable', filter="PartitionKey eq 'tasksSeattle'")
for task in tasks:
    print(task.description)
    print(task.priority)
    print(task.PartitionKey)
    print(task.RowKey)
    print("-------")
Take out the trash
200
tasksSeattle
001
-------
Wash the car
100
tasksSeattle
002
-------

本篇實作有另外建立Jupyter Notebook並更新requirements,想動手試試看的朋友可以參考喔!


Amos3.0 團隊系列文

以下為團隊所有成員的主題,也歡迎大家前往欣賞喔!


上一篇
多功能倉庫 - Storage
下一篇
開發部署大平台 - App Service
系列文
用Azure建立一條龍的服務30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言