最近在搞資源上傳,用腳本去上傳180g的資源,以及後臺要做資源之間的映射匹配什麼鬼的。真的是有趣呢。
一邊寫腳本,一邊總結出這個七牛工具包,才4個小函數。。
github:https://github.com/emaste-r/MyQiniuUtil/tree/master
# coding=utf-8
from qiniu import Auth, put_file, etag
from qiniu import BucketManager # 構建鑑權對象
class MyQiniuUtil(object):
"""
處理七牛的工具類
"""
access_key = "your-access-key"
secret_key = "your-secret-key"
bucket_name = 'your-bucket-name'
@classmethod
def upload(cls, file_path):
"""
上傳文件
:param file_path: 文件路徑
:return: key
"""
# 構建鑑權對象
q = Auth(cls.access_key, cls.secret_key)
# 上傳到七牛後保存的文件名
key = None
# 生成上傳 Token,可以指定過期時間等
token = q.upload_token(cls.bucket_name, key, 3600)
# 要上傳文件的本地路徑
ret, info = put_file(token, key, file_path)
assert ret['hash'] == etag(file_path)
return ret['key']
@classmethod
def get_img_info(cls, img_url):
"""
獲取七牛上圖片的基本信息:長寬、後綴
:param img_url:
:return: tuple(長、寬、後綴)
"""
info_url = img_url + '?imageInfo' # 基本信息
import requests
r = requests.get(info_url)
body = r.content
r.close()
import json
info_dic = json.loads(body)
height = info_dic['height']
width = info_dic['width']
suffix = info_dic['format']
return height, width, suffix
@classmethod
def get_key(cls, file_path):
"""
獲取一個文件的key,七牛的算法是獲取文件的hash值,使用的是 qiniu.etag()
:param file_path:
:return: key (str)
"""
key = etag(file_path)
return key
@classmethod
def check_file_exist(cls, file_path):
"""
判斷key在你空間中存在
:param file_path:
:param bucket_name:
:return: True False
"""
key = cls.get_key(file_path)
# 初始化Auth狀態
q = Auth(cls.access_key, cls.secret_key)
# 初始化BucketManager
bucket = BucketManager(q)
ret, info = bucket.stat(cls.bucket_name, key)
text_body = info.text_body
if 'error' in text_body:
return False
return True
if __name__ == '__main__':
# 文件
file_path = u"/Users/ouyang/Desktop/新增測試/淨空法師/封面.jpg"
# 上傳, 返回key
key = MyQiniuUtil.upload(file_path)
print key
# 獲取文件key
key = MyQiniuUtil.get_key(file_path)
print key
# 判斷文件是否存在
is_exist = MyQiniuUtil.check_file_exist(file_path)
print is_exist