如何使用七牛Python SDK寫一個同步指令碼及使用教程

來源:互聯網
上載者:User
七牛雲端儲存的 Python 語言版本 SDK(本文以下稱 Python-SDK)是對七牛雲端儲存API協議的一層封裝,以提供一套對於 Python 開發人員而言簡單易用的開發工具。Python 開發人員在對接 Python-SDK 時無需理解七牛雲端儲存 API 協議的細節,原則上也不需要對 HTTP 協議和原理做非常深入的瞭解,但如果擁有基礎的 HTTP 知識,對於出錯情境的處理可以更加高效。

最近剛搭了個markdown靜態部落格,想把圖片放到雲端儲存中。

經過調研覺得七牛可以滿足我個人的需求,就選它了。

要引用圖片就要先將圖片上傳到雲上。

雖然七牛網站後台可以上傳檔案,但每次上傳都需要先登入,然後選擇圖片,設定串連地址,才能上傳。

這個過程有些繁瑣,所以我便想用七牛雲提供的SDK寫個一同步工具,方便增量同步處理檔案。

有了這個想法,就馬上行動。花了大概一個上午的時間,總算把這個工具給寫出來,並放到GitOSC和github上。

#!/usr/bin/env python#-*- coding:utf-8 -*-# # AUTHOR = "heqingpan"# AUTHOR_EMAIL = "heqingpan@126.com"# URL = "http://git.oschina.net/hqp/qiniu_sync"import qiniufrom qiniu import Authfrom qiniu import BucketManagerimport osimport reaccess_key = ''secret_key = ''bucket_name = ''bucket_domain = ''q = Auth(access_key, secret_key)bucket = BucketManager(q)basedir=os.path.realpath(os.path.dirname(__file__))filename=__file__ignore_paths=[filename,"{0}c".format(filename)]ignore_names=[".DS_Store",".git",".gitignore"]charset="utf8"diff_time=2*60def list_all(bucket_name, bucket=None, prefix="", limit=100): rlist=[] if bucket is None:  bucket = BucketManager(q) marker = None eof = False while eof is False:  ret, eof, info = bucket.list(bucket_name, prefix=prefix, marker=marker, limit=limit)  marker = ret.get('marker', None)  for item in ret['items']:   rlist.append(item["key"]) if eof is not True:  # 錯誤處理  #print "error"  pass return rlistdef get_files(basedir="",fix="",rlist=None,ignore_paths=[],ignore_names=[]): if rlist is None:  rlist=[] for subfile in os.listdir(basedir):  temp_path=os.path.join(basedir,subfile)  tp=os.path.join(fix,subfile)  if tp in ignore_names:   continue  if tp in ignore_paths:   continue  if os.path.isfile(temp_path):   rlist.append(tp)  elif os.path.isdir(temp_path):   get_files(temp_path,tp,rlist,ignore_paths,ignore_names) return rlistdef get_valid_key_files(subdir=""): basedir=subdir or basedir files = get_files(basedir=basedir,ignore_paths=ignore_paths,ignore_names=ignore_names) return map(lambda f:(f.replace("\\","/"),f),files)def sync(): qn_keys=list_all(bucket_name,bucket) qn_set=set(qn_keys) l_key_files=get_valid_key_files(basedir) k2f={} update_keys=[] u_count=500 u_index=0 for k,f in l_key_files:  k2f[k]=f  str_k=k  if isinstance(k,str):   k=k.decode(charset)  if k in qn_set:   update_keys.append(str_k)   u_index+=1   if u_index > u_count:    u_index-=u_count    update_file(k2f,update_keys)    update_keys=[]  else:   # upload   upload_file(k,os.path.join(basedir,f)) if update_keys:  update_file(k2f,update_keys) print "sync end"def update_file(k2f,ulist): ops=qiniu.build_batch_stat(bucket_name,ulist) rets,infos = bucket.batch(ops) for i in xrange(len(ulist)):  k=ulist[i]  f=k2f.get(k)  ret=rets[i]["data"]  size=ret.get("fsize",None)  put_time = int(ret.get("putTime")/10000000)  local_size=os.path.getsize(f)  local_time=int(os.path.getatime(f))  if local_size==size:   continue  if put_time >= local_time - diff_time:   # is new   continue  # update  upload_file(k,os.path.join(basedir,f))def upload_file(key,localfile): print "upload_file:" print key token = q.upload_token(bucket_name, key) mime_type = get_mime_type(localfile) params = {'x:a': 'a'} progress_handler = lambda progress, total: progress ret, info = qiniu.put_file(token, key, localfile, params, mime_type, progress_handler=progress_handler)def get_mime_type(path): mime_type = "text/plain" return mime_typedef main(): sync()if __name__=="__main__": main()

這個同步指令碼支援批量比較檔案,差異累加式更新、批次更新。

使用方式

安裝七牛Python SDK

pip install qiniu

填寫指令檔(qiniusync.py)的配置資訊

access_key = ''secret_key = ''bucket_name = ''

註冊後可以拿到對應的資訊

將指令檔(qiniusync.py)拷貝到待同步根目錄

運行指令碼

python qiniusync.py

後記

寫完提交之後才發現,七牛已經提供相應的工具,我這個算是重複造輪子吧。

既然已經寫,就發出來,當做熟悉一下七牛的SDK也不錯,說不定以後還能用的上。

七牛雲端儲存Python SDK使用教程

本教程旨在介紹如何使用七牛的Python SDK來快速地進行檔案上傳,下載,處理,管理等工作。

安裝

首先,要使用Python的SDK必須要先安裝。七牛的Python SDK是開源的,託管在Github上面,項目地址為 https://github.com/qiniu/python-sdk 。

安裝的方式可以如項目的說明上所說,用 pip install qiniu 。當然也可以直接 clone 一份原始碼下來直接使用。我一般喜歡直接 clone 原始碼,這樣的話,如果要對SDK做一些改動也是十分容易的。

最新版本的Python SDK需要依賴 requests 庫,所以要提前安裝好。安裝方式當然也可以用 pip install requests 。

開發環境

Python的開發環境有很多種選擇,如果喜歡文本的方式,比如vim,emacs,sublime text等都是很好的選擇,如果你喜歡IDE,那麼最流行的莫過於 PyCharm 了。 PyCharm 的最新版本到 這裡下載。

Access Key和Secret Key

我們知道七牛雲端儲存的許可權校正機制基於一對密鑰,分別稱為 Access Key 和 Secret Key 。其中 Access Key 是公開金鑰, Secret Key 是私密金鑰。這一對密鑰可以從七牛的後台擷取。

小試牛刀

好了,做了上面的這些準備工作,我們就去上傳一個簡單的檔案,練練手。

python#coding=utf-8__author__ = 'jemy''''

本例示範了一個簡單的檔案上傳。

這個例子裡面,sdk根據檔案的大小選擇是Form方式上傳還是分區上傳。

'''import qiniuaccessKey = ""secretKey = ""#解析結果def parseRet(retData, respInfo): if retData != None: print("Upload file success!") print("Hash: " + retData["hash"]) print("Key: " + retData["key"]) #檢查擴充參數 for k, v in retData.items():  if k[:2] == "x:":  print(k + ":" + v) #檢查其他參數 for k, v in retData.items():  if k[:2] == "x:" or k == "hash" or k == "key":  continue  else:  print(k + ":" + str(v)) else: print("Upload file failed!") print("Error: " + respInfo.text_body)#無key上傳,http請求中不指定key參數def upload_without_key(bucket, filePath): #產生上傳憑證 auth = qiniu.Auth(accessKey, secretKey) upToken = auth.upload_token(bucket, key=None) #上傳檔案 retData, respInfo = qiniu.put_file(upToken, None, filePath) #解析結果 parseRet(retData, respInfo)def main(): bucket = "if-pbl" filePath = "/Users/jemy/Documents/jemy.png" upload_without_key(bucket, filePath)if __name__ == "__main__": main()

運行結果為:

Upload file success!
Hash: Fp0XR6tM4yZmeiKXw7eZzmeyYsq8
Key: Fp0XR6tM4yZmeiKXw7eZzmeyYsq8

從上面我們可以看到,使用七牛的Python SDK上傳檔案的最基本的步驟是:

1.產生上傳憑證

2.上傳檔案

3.解析回複結果

小結

綜上所述,其實使用七牛的SDK來上傳檔案還是很簡單的,接下來的教程,我們將在這個例子的基礎上逐步瞭解更多關於檔案上傳的知識。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.