class UpYunStorage(Storage, ThumbnailSupportMixin): """UpYun Storage class for Django pluggable storage system.""" def __init__(self, bucket=BUCKET_NAME, bucket_url=BUCKET_URL, enable_link_token=ENABLE_LINK_TOKEN, link_token=LINK_TOKEN, link_expiration=LINK_EXPIRATION, operator_name=OPERATOR_NAME, operator_password=OPERATOR_PASSWORD): self.bucket = bucket self.operator_name = operator_name self.operator_password = operator_password self.bucket_url = bucket_url self.enable_link_token = enable_link_token self.link_token = link_token self.link_expiration = link_expiration if not bucket or not operator_name or not operator_password: raise ImproperlyConfigured('bucket , opeartor_name, operator_password is requied') self.upyun_client = UpYun(self.bucket, self.operator_name, self.operator_password) def _open(self, name, mode='rb'): if 'w' not in mode and not self.exists(name): raise IOError('File does not exist: %s' % name) return UpYunStorageFile(name, mode, self) def _save(self, name, content): print 'try to save ....', name self._put_file(name, content.read()) content.close() return name def _put_file(self, name, content): name = self._clean_name(name) self.upyun_client.writeFile(name, content, auto=True) def _read(self, name): name = self._clean_name(name) content = self.upyun_client.readFile(name) if content is None: raise UpYunStorageException('fail to read file content') return content def _clean_name(self, name): if type(name) is unicode: return name.encode('utf-8') else: return name #def get_valid_name(self, name): # print 'get valid name', name # return name def listdir(self, path): return [d.filename for d in self.upyun_client.readDir(path)] def delete(self, name): try: return self.upyun_client.delete(name) except UpYunException: raise UpYunStorageException(unicode(UpYunException)) def exists(self, name): try: return self.upyun_client.getFileInfo(name) is not None except UpYunException: raise UpYunStorageException(unicode(UpYunException)) def size(self, name): try: fileinfo = self.upyun_client.getFileInfo(name) except UpYunException: raise UpYunStorageException(unicode(UpYunException)) if not fileinfo: raise UpYunStorageException('file %s not exists' %name) return fileinfo['size'] def url(self, name): if not self.bucket_url: raise ImproperlyConfigured('bucket_url is required for url method') if self.enable_link_token and not self.link_token: raise ImproperlyConfigured('link token is required , if enalbe_link_token is on') url = urlparse.urljoin(self.bucket_url, name) if self.enable_link_token: etime = int(time.time() + self.link_expiration) if name[0] != '/': name = '/' + name sign = hashlib.md5('%s&%s&%s' %(self.link_token,etime,name)).hexdigest()[12:20] + str(etime) url = url + '?_upt=' + sign return url