前言
欢迎大家来我的博客一起学习: http://hackergu.com
写博客的时候经常要用到七牛云存储图片,但是每次点开官网上传又显得过于麻烦,所以用python写了如下脚本用于图片上传。
qiniu_upload
以下就是脚本的全部内容,其中的一些内容大家根据自己的实际情况自行修改。
用法展示:
python qiniu_upload.py -p example.png
#!/usr/bin/python
# -*- coding: utf-8 -*-
import qiniu
import re
from optparse import OptionParser
usage = "usage: \n\tpython %prog -p example.png"
parser = OptionParser(usage=usage)
parser.add_option("-p","--picture",dest="pic",
help="the name of picture, like abc.png")
(options, args) = parser.parse_args()
#替换为自己的ak和sk
access_key = '**************************************'
secret_key = '**************************************'
#替换为自己的域名
url = 'domain.com'
#替换为自己的仓库名
bucket_name = 'example'
q = qiniu.Auth(access_key, secret_key)
#图片返回地址,http或者https由自己来决定
def qiniu_upload(key, localfile):
token = q.upload_token(bucket_name, key, 3600)
ret, info = qiniu.put_file(token, key, localfile)
if ret:
return '图片地址:\n\thttp://{0}/{1}'.format(url, ret['key'])
else:
raise UploadError('上传失败,请重试')
def main():
key_ini = str(re.findall(r'[^\\/:*?"<>|\r\n]+$', options.pic))
key = key_ini.strip("['").strip("']")
localfile = str(options.pic)
res = qiniu_upload(key, localfile)
print(res)
if __name__ == '__main__':
if not options.pic:
parser.error("options error, please use -h or --help to get help")
else:
main()