如何使用七牛pythonsdk写一个同步脚本及使用教程

七牛云存储的 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 qiniu
from qiniu import auth
from qiniu import bucketmanager
import os
import re
access_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*60
def 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 rlist
def 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 rlist
def 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_type
def 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 qiniu
accesskey = “”
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来上传文件还是很简单的,接下来的教程,我们将在这个例子的基础上逐步了解更多关于文件上传的知识。

Posted in 未分类

发表评论