七牛云第三方资源获取(python)

研究了半天总算搞清楚七牛云的第三方资源获取,在这里开源一下

class SaveImage(object):
    def __init__(self):
        # Access Key 和 Secret Key
        self.access_key = 'YourAK'
        self.secret_key = 'YourSK'
        # 构建鉴权对象
        self.q = Auth(self.access_key, self.secret_key)
        # 要上传的空间
        self.bucket_name = ''

    @staticmethod
    def hash_url(url):
        """将urlhash化"""
        fp = hashlib.sha1()
        fp.update(url.encode('utf-8'))
        return fp.hexdigest()
        
	def check_upload(self, url):
        """检查图片是否已经上传过, 未上传返回612状态码,已经上传则是200"""
        bucket = BucketManager(self.q)
        ret, info = bucket.stat(self.bucket_name, self.hash_url(url))
        print(info.status_code)
        if info.status_code == 612:
            return 0
        else:
            return 1
            
    def post_url_to_download(self, url):
        """发送url到七牛云,第三方下载图片并保存"""
        EncodedURL = urlsafe_base64_encode(url)
        EncodedEntryURL = entry(self.bucket_name, self.hash_url(url))
        mid_url = '/fetch/{}/to/{}'.format(EncodedURL, EncodedEntryURL)
        api_url = 'http://iovip.qbox.me' + mid_url
        content_type = 'application/x-www-form-urlencoded'
        authorization = self.q.token_of_request(url=mid_url, content_type=content_type)
        # print(authorization)
        headers = {
            'Authorization': 'QBox ' + authorization,
            'Host': 'iovip.qbox.me',
            # 'Content-Length': '299',
            'Content-Type': content_type,
            # 'Connection': 'keep-alive',
        }
        res = requests.post(api_url, headers=headers, timeout=30)
        print(res.content)
        print(res.status_code)
        print(res.headers)

返回200就是成功,可以使用check函数查询是否上传成功

你可能感兴趣的:(技术笔记,编程工具详解)