七牛云存儲的 Python 語言版本 SDK(本文以下稱 Python-SDK)是對七牛云存儲API協議的一層封裝,以提供一套對于 Python 開發者而言簡單易用的開發工具。Python 開發者在對接 Python-SDK 時無需理解七牛云存儲 API 協議的細節,原則上也不需要對 HTTP 協議和原理做非常深入的了解,但如果擁有基礎的 HTTP 知識,對于出錯場景的處理可以更加高效。
最近剛搭了個markdown靜態博客,想把圖片放到云存儲中。
經過調研覺得七??梢詽M足我個人的需求,就選它了。
要引用圖片就要先將圖片上傳到云上。
雖然七牛網站后臺可以上傳文件,但每次上傳都需要先登錄,然后選擇圖片,設置連接地址,才能上傳。
這個過程有些繁瑣,所以我便想用七牛云提供的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("http://","/"),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 = "<Your Access Key>"secretKey = "<Your Secret Key>"#解析結果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來上傳文件還是很簡單的,接下來的教程,我們將在這個例子的基礎上逐步了解更多關于文件上傳的知識。
新聞熱點
疑難解答
圖片精選