问题描述

在微软云环境中,使用python SDK连接存储账号(Storage Account)需要计算Blob大小?虽然Azure提供了一个专用工具Azure Storage Explorer可以统计出Blob的大小:

但是它也是只能一个Blob Container一个的统计,如果Container数量巨大,这将是一个繁琐的工作。而作为开发者,应该让代码来帮助完成。下文使用最快上手的Python代码来计算Blob中容量的大小。

完整代码

import os, uuid, datetime, threading
import logging
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient, __version__ def calculateBlob(connect_string, count):
try:
blob_service_client = BlobServiceClient.from_connection_string(connect_string)
except Exception as e:
messages = str(count) + "Connect_String Error, Messages:" + e.args.__str__()
print(messages)
logging.info(messages)
else:
all_containers = blob_service_client.list_containers()
for c in all_containers:
count_name = c.name
print(count_name)
if count_name not in blobSize_Total:
blobSize_Total[count_name] = 0
if count_name not in blobSize_Daily:
blobSize_Daily[count_name] = 0
container_client = blob_service_client.get_container_client(count_name)
generator = container_client.list_blobs() total_size_container = 0
daily_size_container = 0 for blob in generator:
total_size_container += blob.size
blob_create_time = blob.creation_time.strftime("%Y%m%d")
if blob_create_time != now_date:
continue
else:
# Calculate BlobSize in this month
daily_size_container += blob.size
# blobSize_Daily[count_name] += blob.size # /(1024*1024) # content_length - bytes blobSize_Total[count_name] += total_size_container / (1024 * 1024)
blobSize_Daily[count_name] += daily_size_container / (1024 * 1024) return None if __name__ == '__main__':
# connect string
Connection_String_List ="DefaultEndpointsProtocol=https;AccountName=<storagename>;AccountKey=<key>;EndpointSuffix=core.chinacloudapi.cn"
# for i in Connection_String:
start = datetime.datetime.now()
print(start) # 定义全局变量 - blobSize_Daily & blobSize_Total
blobSize_Daily = {}
blobSize_Total = {} now_date = datetime.datetime.now().strftime("%Y%m%d") print("开始计算")
calculateBlob(Connection_String_List, 1)
print("计算完成") print("统计当前新增大小")
print(blobSize_Daily)
print("统计Blob总大小")
print(blobSize_Total)
end = datetime.datetime.now()
print(end)

如运行是没有Azure blob模块,可以使用 pip install azure-storage-blob 安装。以上代码运行结果如下:

如果有多个Storage Account,可以考虑加入多线程的方式来运行,在代码中增加一个myThread类,然后在 __main__ 中把 calculateBlob(Connection_String_List, 1) 运行替换为 many_thread(Connection_String_List) 即可。

class myThread(threading.Thread):

    def __init__(self, threadID, name, connection_string):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.connection_string = connection_string def run(self):
print("开始线程:" + self.name)
calculateBlob(self.connection_string, self.threadID)
print("退出线程:" + self.name) def many_thread(Connection_String_List):
threads = []
for i in range(len(Connection_String_List)): # 循环创建32个线程
t = myThread(i, "Thread-" + str(i), Connection_String_List[i])
threads.append(t)
for t in threads: # 循环启动32个线程 - 对应64个storage account
t.start()
for t in threads:
t.join()

遇见问题

在多线程执行时,可能会遇见问题:("Connection broken: ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None)", ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None)),出现此问题大都是由于客户端使用了已经断开的连接导致所导致的。所以一定要仔细调试多线程关闭代码。是否是把还需要运行的线程给关闭了。导致了以上的错误消息。

附录一:多线程计算Blob的完整代码

import os, uuid, datetime, threading
import logging
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient, __version__ def calculateBlob(connect_string, count):
try:
blob_service_client = BlobServiceClient.from_connection_string(connect_string)
except Exception as e:
messages = str(count) + "Connect_String Error, Messages:" + e.args.__str__()
print(messages)
logging.info(messages)
else:
all_containers = blob_service_client.list_containers()
for c in all_containers:
count_name = c.name
print(count_name)
if count_name not in blobSize_Total:
blobSize_Total[count_name] = 0
if count_name not in blobSize_Daily:
blobSize_Daily[count_name] = 0
container_client = blob_service_client.get_container_client(count_name)
generator = container_client.list_blobs() total_size_container = 0
daily_size_container = 0 for blob in generator:
total_size_container += blob.size
blob_create_time = blob.creation_time.strftime("%Y%m%d")
if blob_create_time != now_date:
continue
else:
# Calculate BlobSize in this month
daily_size_container += blob.size
# blobSize_Daily[count_name] += blob.size # /(1024*1024) # content_length - bytes blobSize_Total[count_name] += total_size_container / (1024 * 1024)
blobSize_Daily[count_name] += daily_size_container / (1024 * 1024) return None class myThread(threading.Thread): def __init__(self, threadID, name, connection_string):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.connection_string = connection_string def run(self):
print("开始线程:" + self.name)
calculateBlob(self.connection_string, self.threadID)
print("退出线程:" + self.name) def many_thread(Connection_String_List):
threads = []
for i in range(len(Connection_String_List)): # 循环创建32个线程
t = myThread(i, "Thread-" + str(i), Connection_String_List[i])
threads.append(t)
for t in threads: # 循环启动32个线程 - 对应64个storage account
t.start()
for t in threads:
t.join() if __name__ == '__main__':
# connect string
Connection_String_List = ['DefaultEndpointsProtocol=https;AccountName=<your storage account 1>;AccountKey=<Key 1>;EndpointSuffix=core.chinacloudapi.cn', 'DefaultEndpointsProtocol=https;AccountName=<your storage account 2>;AccountKey=<Key 2>;EndpointSuffix=core.chinacloudapi.cn']
# for i in Connection_String:
start = datetime.datetime.now()
print(start) # 定义全局变量 - blobSize_Daily & blobSize_Total
blobSize_Daily = {}
blobSize_Total = {} now_date = datetime.datetime.now().strftime("%Y%m%d") many_thread(Connection_String_List)
print("Main Thread End") print(blobSize_Daily)
print(blobSize_Total)
end = datetime.datetime.now()
print(end)

运行效果:

参考资料

快速入门:使用 Python v12 SDK 管理 blobhttps://docs.azure.cn/zh-cn/storage/blobs/storage-quickstart-blobs-python

Python 列表(List)https://www.runoob.com/python/python-lists.html

BlobServiceClient Classhttps://docs.microsoft.com/en-us/python/api/azure-storage-blob/azure.storage.blob.blobserviceclient?view=azure-python

 

【Azure Developer】使用 Python SDK连接Azure Storage Account, 计算Blob大小代码示例的更多相关文章

  1. 使用Python SDK管理Azure Load Balancer

    概述 下面将演示如何使用Python SDK管理中国区Azure Load balancer.关于Azure负载均衡器的详细功能介绍,请参考官方文档. Code Sample import os fr ...

  2. 【Azure Developer】Python 获取Micrisoft Graph API资源的Access Token, 并调用Microsoft Graph API servicePrincipals接口获取应用ID

    问题描述 在Azure开发中,我们时常面临获取Authorization问题,需要使用代码获取到Access Token后,在调用对应的API,如servicePrincipals接口. 如果是直接调 ...

  3. 【Azure Developer】Python代码通过AAD认证访问微软Azure密钥保管库(Azure Key Vault)中机密信息(Secret)

    关键字说明 什么是 Azure Active Directory?Azure Active Directory(Azure AD, AAD) 是 Microsoft 的基于云的标识和访问管理服务,可帮 ...

  4. 【Azure Developer】调用SDK的runPowerShellScript方法,在Azure VM中执行PowerShell脚本示例

    当需要通过代码的方式执行PowerShell脚本时,可以参考以下的示例. Azure SDK中提供了两个方法来执行PowerShell脚本 (SDK Source Code: https://gith ...

  5. 【Azure Developer】使用Postman获取Azure AD中注册应用程序的授权Token,及为Azure REST API设置Authorization

    Azure Active Directory (Azure AD) is Microsoft's cloud-based identity and access management service, ...

  6. 【Azure Developer】解决Azure Key Vault管理Storage的示例代码在中国区Azure遇见的各种认证/授权问题 - C# Example Code

    问题描述 使用Azure密钥保管库(Key Vault)来托管存储账号(Storage Account)密钥的示例中,从Github中下载的示例代码在中国区Azure运行时候会遇见各种认证和授权问题, ...

  7. 【Azure Developer】【Python 】使用 azure.identity 和 azure.common.credentials 获取Azure AD的Access Token的两种方式

    问题描述 使用Python代码,展示如何从Azure AD 中获取目标资源的 Access Token. 如要了解如何从AAD中获取 client id,client secret,tenant id ...

  8. 【Azure Developer】使用Microsoft Graph API 批量创建用户,先后遇见的三个错误及解决办法

    问题描述 在先前的一篇博文中,介绍了如何使用Microsoft Graph API来创建Azure AD用户(博文参考:[Azure Developer]使用Microsoft Graph API 如 ...

  9. 【Azure 应用服务】Azure Function集成虚拟网络,设置被同在虚拟网络中的Storage Account触发,遇见Function无法触发的问题

    一切为了安全,所有的云上资源如支持内网资源访问,则都可以加入虚拟网络 问题描述 使用Azure Function处理Storage Account中Blob 新增,更新,删除等情况.Storage A ...

随机推荐

  1. OO第四单元总结与课程总结

    OO第四单元总结与课程总结 第四单元作业架构设计 总体分析:本单元作业的需求集中于对UML类图进行查询.对于查询操作来说自然的想法是提前预见到需要查询的内容,在一开始就采用适当的数据结构将必要的信息进 ...

  2. UVA10827球面上的最大和

    题意:      最大子矩阵的加强版,就是给你一个n*n的矩阵,每个格子里面都有数字,然后我们在里面选择一个矩阵,使得矩阵中所有数字的和最大,而且这个题目说这个n*n的矩阵的最右边和最左边是相邻的,最 ...

  3. JAVA反序列化漏洞复现

    目录 Weblogic反序列化漏洞 Weblogic < 10.3.6 'wls-wsat' XMLDecoder 反序列化漏洞(CVE-2017-10271) Weblogic WLS Cor ...

  4. mongoDB常用

    登陆{ 本地的话直接mongo,如果是docker直接就这样docker exec -it 2d71a13e3128 mongo 或者直接这样 mongo 127.0.0.1:27017 } 退出是 ...

  5. python-内置函数-文件操作

    文件操作 用的最多的就是r+,w+和a+都有局限性 w+是先清空,然后再写,之后再读 a+是无论如何调整指针位置,写时都在文件最后追加 而r+可以通过调整指针位置来确定写入的位置 文件操作之with处 ...

  6. 五、postman公共函数及newman运行与生成测试报告

    一.公共函数 postman中定义公共函数如下 1.每次断言的时候都需要重写或者复制之前的断言代码,可以通过如下方法定义断言的公共函数,以后每次断言的时候只需要调用公共函数即可进行断言 设置公共函数对 ...

  7. 在服务器上使用 smart http 搭建 Git 服务器

    前言 最近一直在写 django 网页的代码,随着代码的量越来越大,管理起来也有点复杂(当然,有在使用 git 进行代码管理).同时由于有不同的工作环境,有些工作环境对 ssh 的访问有限制,所以想到 ...

  8. DirectX渲染时Clear无效的原因(造成叠影)

    最近在开发D3D程序的过程中,发现一件很奇怪的事情,就是在Render的时候,纹理总是留有"残影"(即上次Render后的帧):如上图,是一副纹理绕中心点旋转的向日葵,但是可以看到 ...

  9. FHD 4K 8K分辨率

    4K(2160P,即4096×2160的像素分辨率)和8K(4320P,即7,680 × 4,320的像素分辨率)属于UHDTV. FHD是FULL HD(Full High Definition)的 ...

  10. ES6学习-3 const

    const声明一个只读的常量.一旦声明,常量的值就不能改变,所以在声名时就进行赋值. const的作用域与let命令相同,只在声明所在的块级作用域内有效. const命令声明的常量,同样存在暂时性死区 ...