AWS已在中國落地!詳情請猛擊此處。
S3是AWS中的存儲服務,為使用者随時随地存儲和通路大量資料提供了Web service接口,為開發者提供了一種可以快速低廉通路資料存儲的服務。并且,開發者可以利用s3實作ec2通路大量的資料資源。其價格低廉,受到了廣泛開發者的青睐。
s3中均是以bucket,key來區分資料,類似與檔案系統中的檔案夾,檔案的概念。有所不同的是,s3中沒有檔案系統中的層級關系,隻有bucket-key兩層,key儲存在指定的bucket中。當然key的名稱可以自己定義,你可以将‘/'添加在key名字中(如'dir1/dir2/file'),以作為子檔案夾,但s3并不會将其視為檔案夾的層級結構,在檢視bucket的key時,傳回的結果也不會考慮。
既然是Web service,那麼其使用方式就是set_contents_from_file非常簡單的,不外乎兩種形式,一種是用AWS的command line工具(cli),另一種是aws利用各種開發語言的sdk進行資料的存儲、通路、修改。下面分别簡單介紹cli和aws在python中的sdk boto中,s3的使用方法。
1. cli
在這裡我們假設已經配置好cli的key,關于配置可以參看此文。
與shell風格類似地,cli提供了以下幾種對s3的方法:
單個檔案操作:
cp, mv, rm (single local file and s3 object operations)
檔案夾相關操作:
sync, mb, rb, ls (directory and s3 prefix operations)
其中,對于檔案夾操作,可以利用--recursive和--exclude實作檔案夾的遞歸操作以及過濾操作。
檢視目前帳戶中的所有buckets
When you may need to specify the region of the bucket
# Uploading local files onto s3
# A sync command makes it easy to synchronize the contents of a local folder with a copy in an S3 bucket.
You can also get help with the command:<code></code>
2.boto
在這裡我們假設已經配置好boto的key,關于配置可以參看此文。
1)建立s3的連接配接:
2)建立bucket:
你需要注意你的bucket_name的設定,可以将其考慮成域名的格式,使用period(.)進行層級劃分,關于bucket_name設定的規則請猛擊這裡。
你可以通過設定location來安排你上傳的位置,預設是us-east-1,其他位置如下:
<code></code>
<dl><dd></dd></dl>
需要注意的是,在建立bucket你有可能遇到
建立bucket時你有可能會遇到S3CreateError的異常,傳回BucketAlreadExists的錯誤,這是由于在s3中所有使用者的bucket都放在同一層,如果你建立的bucket名稱比較常見,如test,則很有可能已被其他使用者使用,進而出現該問題。
在boto的reference文檔中提到了這一點,原文如下:
"Well, the thing you have to know aboutbuckets is that they are kind of like domain names. It’s one flat namespace that everyone who uses S3 shares. So, someone has already createa bucket called “mybucket” in S3 and that means no one else can grab that bucket name. So, you have to come up with a name that hasn’t been taken yet.For example, something that uses a unique string as a prefix. YourAWS_ACCESS_KEY (NOT YOUR SECRET KEY!) could work but I’ll leave it toyour imagination to come up with something. I’ll just assume that youfound an acceptable name."
3)設定bucket的通路控制規則:
4)寫入key:
或者使用set_contents_from_file
5)讀取所有的key
需要注意的是get_all_buckets()函數是一個底層的實作,其一次最多傳回1000個key(one paging of results),是以在實際中可以使用以下方式
更多關于boto操作s3,可以參看boto的reference
http://boto.readthedocs.org/en/latest/ref/s3.html
後面我還會介紹如何使用boto操作ec2,并在ec2上建構、配置自己的hadoop平台,敬請關注!