Python 操作 Azure Blob Storage

笔者在《Azure 基础:Blob Storage》一文中介绍了 Azure Blob Storage 的基本概念,并通过 C# 代码展示了如何进行基本的操作。最近笔者需要在 Linux 系统中做类似的事情,于是决定使用 Azure 提供的 Azure Storage SDK for Python 来操作 Blob Storage。这样今后无论在 Windows 上还是 Linux上,都用 Python 就可以了。对 Azure Blob Storage 概念还不太熟悉的同学请先参考前文

安装 Azure Storage SDK for Python

最简单的方式是在安装了 python 和 pip 的机器上直接执行下面的命令:

pip install azure-storage

安装完成后通过 pip freeze 命令查看安装的版本:

由于 Azure Storage SDK for Python 是一个开源项目,所以你也可以通过源代码安装它,请参考官方文档

创建 Blob Container

由于任何一个 Blob 都必须包含在一个 Blob Container 中,所以我们的第一个任务是创建 Blob Container。
SDK 为我们提供了一个名为 BlockBlobService 的对象。通过这个对象我们可以创建并操作 Blob Container。下面的代码创建一个名为"nickcon" 的 Container:

代码本身很简单,其中的 account_name 和 account_key 是你的 storage 账号及其访问 key。我们使用 GUI 工具 Microsoft Azure Storage Explorer 查看代码操作的结果:

名为 nickcon 的 Blob Container 已经被成功的创建了。

上传文件

接下来我们要把本地的文件上传到刚才创建的 Blob Container 中。Azure SDK 为我们提供了下面四个方法:

create_blob_from_path #上传指定路径的文件。
create_blob_from_stream #把一个数据流中的内容上传。
create_blob_from_bytes #上传一个 bype 数组。
create_blob_from_text #使用特定的编码格式上传字符串。

是的,你没有看错,所有方法的名字中都没有 upload 字眼,而是使用了 create。这也说明上传文件的本质是在云端创建一个 Blob 对象。

复制代码
from azure.storage.blob import BlockBlobService
from azure.storage.blob import ContentSettings

mystoragename = "xxxx"
mystoragekey = "yyyy"
blob_service = BlockBlobService(account_name=mystoragename, account_key=mystoragekey)

blob_service.create_blob_from_path(
    'nickcon',
    'myblobcortana.jpg',
    'cortana-wallpaper.jpg',
    content_settings=ContentSettings(content_type='image/jpg'))
复制代码

这次我们引入了类型 ContentSettings,主要是指定文件的类型。注意 create_blob_from_path 方法的第二个参数,我们需要为新的 blob 对象指定一个名字。第一个参数是目标 Container, 第三个参数是要上传的本地文件路径。执行上面的脚本,会把本地的一张壁纸 cortana-wallpaper.jpg 上传到 Azure Blob Container 中:

在 Container 中创建的 Blob 对象的名称已经不是源文件的名称了,而是我们指定的 myblobcortana.jpg。

控制访问权限

存放在 Blob Container 中的文件都有对应的 URL,这是 Azure Blob Storage 的默认策略。为的是我们可以从任何地方通过 URL 来访问这些文件。比如 myblobcortana.jpg 文件的 URL 为:

https://nickpsdk.blob.core.windows.net/nickcon/myblobcortana.jpg
直接把这个地址粘贴到浏览器的地址栏里:

啊哦,尴尬了,收到了一个无情的 error!

认真想一下,收到这样的错误是合理的。否则任何人都能看到我保存的文件内容,隐私何在?还会有人为 Azure Blob Storage 付费吗?事情的真相是这样的,默认情况下我们创建的 Blob Container 和 Blob 对象都是私有的,也就是必须通过账号和 access key 才能访问。如果你要想让内容变成大家都能访问的公共资源,可以在创建时指定为 PublicAccess。也可以在创建完成后修改它的属性为 PublicAccess。下面我们把 nickcon Container 设置为 PublicAccess:

复制代码
from azure.storage.blob import BlockBlobService
from azure.storage.blob import PublicAccess

mystoragename = "xxxx"
mystoragekey = "yyyy"
blob_service = BlockBlobService(account_name=mystoragename, account_key=mystoragekey)

blob_service.set_container_acl('nickcon', public_access=PublicAccess.Container)
复制代码

此处 import 了 PublicAccess 类型,并调用 set_container_acl 方法来修改 Container 的访问权限。试试重新刷新一下网页:

此时就不要再往你的 Blob Container 中放隐私照了哦!

列出 Blob Container 中的所有文件

检查 Container 中都有哪些文件是很重要的操作,当然我们可以轻松的完成:

generator = blob_service.list_blobs('nickcon')
for blob in generator:
print(blob.name)

使用 list_blobs 方法可以获得 Container 中的所有 Blob 对象。上面的代码打印了所有 Blob 对象的名称。

下载 Blob 对象

和创建 Blob 对象一样,也有四个方法可以下载 Blob 对象。简单期间我们只演示 get_blob_to_path 方法,其它的用法类似:

blob_service.get_blob_to_path('nickcon', 'myblobcortana.jpg', 'newimage.png')

其中第二个参数为 Container 中 Blob 对象的名称,第三个参数为保存到本地文件的路径。

删除 Blob 对象

有创建自然有删除,代码很简单,不再啰嗦:

blob_service.delete_blob('nickcon', 'myblobcortana.jpg')

备份 Blob Container 中的文件

是的,你没听错!
我们相信云存储的安全性,但把重要的数据备份到其它的存储上也是需要的。下面的代码会把一个 Azure Storage Account 中的所有 Blob Container 中的内容备份到本地磁盘上:

复制代码
from azure.storage.blob import BlockBlobService
import os

mystoragename = "xxxx"
mystoragekey = "yyyy"
blob_service = BlockBlobService(account_name=mystoragename, account_key=mystoragekey)

# 下载一个 Blob Container 中的所有文件
def downloadFilesInContainer(blobContainName):
    generator = blob_service.list_blobs(blobContainName)
    for blob in generator:
        # 获得 Blob 文件的目录路径
        blobDirName =  os.path.dirname(blob.name)
        # 把 Blob Container 的名称也添加为一级目录
        newBlobDirName = os.path.join(blobContainName, blobDirName)
        # 检查文件目录是否存在,不存在就创建
        if not os.path.exists(newBlobDirName):
            os.makedirs(newBlobDirName)
        localFileName = os.path.join(blobContainName, blob.name)
        blob_service.get_blob_to_path(blobContainName, blob.name, localFileName)

# 获得用户所有的 Blob Container
containerGenerator = blob_service.list_containers()
for con in containerGenerator:
    downloadFilesInContainer(con.name)
复制代码

此处需要注意一点,blob.name 包含了文件在 container 中的目录。比如一个文件在 Blob Container 中的路径为 abc/test.txt,那么它的 blog.name 就是 abc/test.txt。要保持文件在 Blob Container 的名称及路径就要在本地创建对应的目录结构。

总结

最后的 demo 可以简单的实现备份所有 Blob 文件的功能。由于微软把相关接口封装的很清晰,所以代码非常的简短。使用 Python 的好处是可以在不同的平台上运行相同的代码。当你需要在不同的操作系统中做同样的事情时,这可太棒了!


本文转自sparkdev博客园博客,原文链接:http://www.cnblogs.com/sparkdev/p/6979802.html,如需转载请自行联系原作者

来源:https://yq.aliyun.com/articles/373061


智能推荐

Windows Azure Storage (11) 计算你存储的Blob的大小

《Windows Azure Platform 系列文章目录》     熟悉Windows Azure的网友都知道,Windows Azure Storage有三种:分别是Blob、Table和Queue。Blob可以存储二进制文件,比如图片、照片、Word、Excel文件等等。而Windows Azure Storage是按需收费的,控制好Blob存储容量的大小可以让我们更好的控制成本...

Azure Blob Storage学习笔记——图片的上传,浏览,下载,删除

 1.通过NuGet将Azure Storage的相关包引入项目 2.在config文件中写入相关帐号 3.Azure的相关操作   4.上传图片 5.浏览图片(通过图片ID查看图片) 6.下载图片  7.删除图片(其实是将图片移动到名为recyclebin的Container里去,方便找回,可以写一个计划任务,定期删除recyclebin里的文件)   注...

[New Portal]Windows Azure Storage (14) 使用Azure Blob的PutBlock方法,实现文件的分块、离线上传...

 《Windows Azure Platform 系列文章目录》   相关内容   Windows Azure Platform (二十二) Windows Azure Storage Service存储服务之Blob详解(上)   Windows Azure Platform (二十三) Windows Azure Storage Service存储服务之Blob详解(中)   Windows ...

使用Azure Blob存储

可以通过多种方式来对Azure Blob进行操作。在此我们介绍通过VS的客户端及代码两种方式来操作Blob。 一、通过VS来操作Blob.    1.首先下载publish settings 文件:打开“https://manage.windowsazure.cn/publishsettings/index”,登陆China Azure,下载publis...

【Azure Services Platform Step by Step-第10篇】使用Blob Storage搭建简单网络硬盘

我们已经介绍过Blob Storage的用途及其在Windows Azure Storage的地位。现在我们示范一下,如何用最简单的代码,将Blob Storage带入我们的生活。 最终效果如下图:(已部署到云端的Demo http://ibm.cloudapp.net/DriveC.aspx  ) 虽然Windows Azure Storage都提供了REST的编程...

猜你喜欢

Azure Storage Explorer 使用

有些时候我们在做迁移的时候为了保证数据安全,建议在不删除原有虚拟机的前提下,复制VHD文件,新建VM 工具:Azure Storage Explorer Download: http://azurestorageexplorer.codeplex.com/ 完成安装(此处省略) 打开storage explorer,配置存储账户 选择ADD Account 回到Azure portal,复制需要的...

Windows Azure Storage

 简单点说Widows Azure Storage就是一个大的网盘,可以让用户存储任何想存储的数据,数据一旦存储到“云”中就永远不会丢失,程序员可以在任何时候,任何终端,任何地点获取任意大小的数据。 目前来说,Windoows Azure Storage 是由4部分组成,如下: 1.Windows Azure Blob Service:主要存储一些大型的Unstruct...

如何更有价值采集数据、高效分析数据?

上回说到,用户行为数据的意义和价值《为什么要进行用户行为分析?》,以及互联网产品用户模型的构建,这其中就包含了对数据的采集和分析两大块儿,本文将从数据采集的三大要点、如何让分析更有价值更高效、以及数据分析思维三部分展开聊。 一、数据采集的三大要点 1、全面性 数据量足够具有分析价值、数据面足够支撑分析需求。 比如对于“查看商品详情”这一行为,需要采集用户触发时的环境信息、会...

shell脚本编程基础(三)

结构化命令(一) if-then和case语句。 If-then-else语句 当if语句中的命令返回非零退出状态码时, bash shell会执行else部分中的命令。 嵌套if-then语句的问题在于代码不易阅读,很难理清逻辑流程。 可以使用else部分的另一种形式:elif。这样就不用再书写多个if-then语句了。 elif使 用另一个if-then语句延续else部分。 elif语句行提...

IBM主机:知天命后再出发

                    第1页:市场究竟还需不需要主机? 第2页:z13改进了什么?第3页:z13还需要改进什么?               ...

问答精选

URL for a user content site and SEO

I was thinking about how i should write my URLs. I want them to A) Be user friendly B) SEO C) allow fast DB queries. The information i have are username, category, mediaId, title and other data i dont...

How to use the Clojure -> macro with an inner function

I'm a Clojure beginner and I want to understand the -> macro This code works: But this doesn't even compile and I don't know how to deal with the error message: CompilerException java.lang.IllegalA...

Java Program to make Tic Tac Toe not working

For my programming class I'm supposed to make a program that simulates a game of tic tac toe. My teacher provided all the methods and said we shouldn't need to add any or take any away, and told us we...

How can i exit the for statement in assembly

The purpose of this code is to flash the bits turned on three times, exit the loop and turn them off. Currently the code seems to be in an infinite loop and does not exit the loop after the count is 0...

Simple Camel test fails with no messages recieved

Am using Spring Boot and I have just added camel to it. I have a simple camel route setup : When I try to create simple test for this route with : It fails with Not sure what could be a problem here. ...

相关问题

相关文章

热门文章

推荐文章

相关标签

推荐问答