使用七牛云存储的Python SDK与Python requests模块可以实现对七牛云存储Bucket内容的备份,Python源码如下。
在运行代码之前,首先需要安装qiniu Python SDK(Release v6.1.9)与Python requests模块,或将这两个包放置在备份脚本的同目录下。
请注意:该源码暂不支持断点续传。脚本运行时,默认在当前目录下创建以bucket_name命名的目录,并将文件备份至该目录下。
#encoding=utf8
#author 在线疯狂
#使用七牛Python SDK与Python requests对Bucket内容做备份
import qiniu.conf
qiniu.conf.ACCESS_KEY = "<YOUR_APP_ACCESS_KEY>"
qiniu.conf.SECRET_KEY = "<YOUR_APP_SECRET_KEY>"
import qiniu.rsf
import requests
import os, errno, sys, shutil
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else: raise
def get_file_from_qiniu(bucket_name, key, cdir):
target = cdir + '/' + key
dir = os.path.dirname(os.path.abspath(target))
if not os.path.isdir(dir):
print '[mkdir_p]', dir
mkdir_p(dir)
url = 'http://' + bucket_name + '.qiniudn.com/' + key
r = requests.get(url, stream=True)
print '[fetch]', url
if r.status_code == 200:
with open(target , 'wb') as f:
r.raw.decode_content = True
shutil.copyfileobj(r.raw, f)
return r.status_code
def listdir(bucket_name, limit = 10, prefix=""):
cdir = os.path.dirname(os.path.abspath(__file__)) + '/' + bucket_name
err = None
marker = None
while err != 'EOF':
rets, err = qiniu.rsf.Client().list_prefix(bucket_name, prefix=prefix, limit=limit, marker=marker)
if err is not None:
sys.stderr.write('error: %s ' % err)
return
#print rets
marker = rets['marker']
for item in rets['items']:
get_file_from_qiniu(bucket_name, item['key'], cdir)
bucket_name = '<YOUR_BUCKET_NAME>'
listdir(bucket_name)
本文链接:http://bookshadow.com/weblog/2014/09/30/qiniu-bucket-backup-python-code/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。